-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution2204.java
More file actions
68 lines (67 loc) · 1.99 KB
/
Copy pathSolution2204.java
File metadata and controls
68 lines (67 loc) · 1.99 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
class Solution2204 {
public int[] distanceToCycle(int n, int[][] edges) {
// 邻接表
List<List<Integer>> adjacentList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjacentList.add(new ArrayList<>());
}
// 度数组
int[] degrees = new int[n];
for (int[] edge : edges) {
adjacentList.get(edge[0]).add(edge[1]);
adjacentList.get(edge[1]).add(edge[0]);
degrees[edge[0]]++;
degrees[edge[1]]++;
}
Deque<Integer> stack = new ArrayDeque<>();
// 将度为1的结点入栈
for (int i = 0; i < n; i++) {
if (degrees[i] == 1) {
stack.addLast(i);
}
}
// 拓扑排序
boolean[] visited = new boolean[n];
while (!stack.isEmpty()) {
int j = stack.removeLast();
visited[j] = true;
for (int k : adjacentList.get(j)) {
if (!visited[k]) {
degrees[k]--;
if (degrees[k] == 1) {
stack.addLast(k);
}
}
}
}
// BFS 求最短路径
stack.clear();
Arrays.fill(visited, false);
int[] res = new int[n];
// 环内节点入队
for (int i = 0; i < n; i++) {
if (degrees[i] > 1) {
stack.addLast(i);
visited[i] = true;
res[i] = 0;
}
}
while (!stack.isEmpty()) {
int j = stack.removeFirst();
visited[j] = true;
for (int k : adjacentList.get(j)) {
if (!visited[k]) {
stack.addLast(k);
res[k] = res[j] + 1;
visited[k] = true;
}
}
}
return res;
}
}