250x250
Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- date
- 스프링부트
- Properties
- 힙덤프
- NIO
- 리소스모니터링
- javascript
- deque
- map
- set
- alter
- math
- JPA
- Union-find
- string
- union_find
- Calendar
- html
- List
- sql
- Java
- 스택
- BFS
- spring boot
- priority_queue
- scanner
- 큐
- dfs
- GC로그수집
- CSS
Archives
- Today
- Total
매일 조금씩
Leet code (Medium) : 1466. Reorder Routes to Make All Paths Lead to the City Zero (DFS) - JAVA 본문
알고리즘/Graph (DFS, BFS)
Leet code (Medium) : 1466. Reorder Routes to Make All Paths Lead to the City Zero (DFS) - JAVA
mezo 2024. 10. 13. 17:39728x90
반응형



방향성이 있는 그래프에서 진입차수 배열에 주어진 방향의 반대방향도 넣어두는 것이 포인트이다.
다만 이 반대방향이 주어진 방향을 뒤집은 방향이라는 것을 알게 하기 위해 음수로 저장했다.
class Solution {
public int minReorder(int n, int[][] connections) {
List<List<Integer>> al = new ArrayList<>();
boolean[] visited = new boolean[n];
for(int i = 0; i < n; i++){
al.add(new ArrayList<>());
}
// 한 방향에 대해서 양방향으로 저장함.
// 이때, 시작점에서 나가는건 양수, 반대는 음수로 저장.
// => 여기선 시작점인 0 부터 차차 탐색하기 때문에, 간선방향이 모두 시작점으로 들어오는 방향이어야 정답이됨.
for(int[] c : connections){
al.get(c[0]).add(c[1]);
al.get(c[1]).add(-c[0]);
}
return dfs(al, visited, 0);
}
public int dfs(List<List<Integer>> al, boolean[] visited, int from){
int change = 0;
visited[from] = true;
for(int to : al.get(from)){
if(!visited[Math.abs(to)]){
// 시작점에서 나가는 방향인 간선일 경우. (방향이 바뀌어야함)
if(to > 0){
change++;
}
change += dfs(al, visited, Math.abs(to));
}
}
return change;
}
}
728x90
반응형
'알고리즘 > Graph (DFS, BFS)' 카테고리의 다른 글
Leet code (Medium) : 1926. Nearest Exit from Entrance in Maze (BFS) - JAVA (0) | 2024.10.13 |
---|---|
Leet code (Medium) : 399. Evaluate Division (DFS) - JAVA (0) | 2024.10.13 |
Leet code (Medium) : 128. Longest Consecutive Sequence - JAVA (0) | 2024.10.13 |
Leet code (Medium) : 207. Course Schedule (BFS) - JAVA (0) | 2024.10.13 |
백준 1388번 : 바닥 장식 C++ dfs (0) | 2021.06.25 |