-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathsol.java
73 lines (64 loc) · 2.3 KB
/
sol.java
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
69
70
71
72
73
import java.util.*;
public class sol {
public static void main(String[] args) {
// enter your sol here
}
class Solution {
public int shortestPathLength(int[][] graph) {
List<List<Integer>> adjacentList = new ArrayList<>();
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> adjacentList.get(a).size() -
adjacentList.get(b).size());
int n = graph.length;
for (int i = 0; i < n; i++) {
List<Integer> list = new ArrayList<>();
for (int node : graph[i]) {
list.add(node);
}
adjacentList.add(list);
queue.add(i);
}
int minLen = Integer.MAX_VALUE;
while (!queue.isEmpty()) {
int start = queue.poll();
int[] visited = new int[n];
getLen(adjacentList, visited, start);
if (!isValid(visited))
continue;
minLen = Math.min(calLen(visited), minLen);
}
return minLen != Integer.MIN_VALUE ? minLen : -1;
}
private int calLen(int[] visited) {
int len = 0;
for (int curr : visited) {
len += curr;
}
return len - 1;
}
private boolean isValid(int[] visited) {
for (int curr : visited) {
if (curr == 0)
return false;
}
return true;
}
private void getLen(List<List<Integer>> adjacentList, int[] visited, int index) {
visited[index]++;
if (isValid(visited))
return;
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> adjacentList.get(a).size() -
adjacentList.get(b).size());
queue.addAll(adjacentList.get(index));
int len = 0;
while (!queue.isEmpty()) {
int curr = queue.poll();
if (queue.size() > 0 && visited[curr] > 0) {
continue;
}
if (!isValid(visited) && visited[curr] < adjacentList.get(curr).size()) {
getLen(adjacentList, visited, curr);
}
}
}
}
}