847. Shortest Path Visiting All Nodes

这题是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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容