这题是BFS的变种,相对还是很难的。
要求求全遍历一张图的最短距离。难的地方在于怎么弄。
我可以从任何一个点出发,找出他遍历所有节点的各种可能的path,然后每种path求一个长度,取最短的,可是这样也太复杂了吧。
求最短距离一般可以想到BFS, 可是我可能还得往回跑。所以一个其实要建一个更高层的图。这个图里面的每一个点是当前位置和需要遍历的点。
每个点就是一个状态, 求的是从任意一个0遍历的状态到全遍历的状态的最小值。
class Solution {
public int shortestPathLength(int[][] graph) {
if (graph == null || graph.length < 2) return 0;
int N = graph.length;
Queue<int[]> queue = new ArrayDeque<>();
Set<Integer> visited = new HashSet<>();
for (int i = 0; i < N; i++) {
queue.offer(new int[]{i, (1 << N) - 1 - (1 << i)});
visited.add(((1 << N) - 1) * N + i);
}
int level = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] state = queue.poll();
int node = state[0], curLeft = state[1];
for (int next : graph[node]) {
int nextLeft = curLeft & ((1 << N) - 1 - (1 << next));
if (nextLeft == 0) return level + 1;
if (visited.add(nextLeft * N + next)) {
queue.offer(new int[] {next, nextLeft});
}
}
}
level++;
}
return -1;
}
}