Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 847. Shortest Path Visiting All Nodes #295

Open
Woodyiiiiiii opened this issue Sep 26, 2023 · 0 comments
Open

Leetcode 847. Shortest Path Visiting All Nodes #295

Woodyiiiiiii opened this issue Sep 26, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

847. Shortest Path Visiting All Nodes

847. Shortest Path Visiting All Nodes

BFS + bitmask

这道题让我想起倒水问题:三个瓶子,容量分别是8、5、3升,初始第一瓶子里有8升水,如何才能构造出4升水?

class Solution {
    public int shortestPathLength(int[][] graph) {
        int n = graph.length;
        int all = (1 << n) - 1;
        Queue<int[]> q = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            q.add(new int[]{1 << i, i, 0});
        }
        Map<Integer, Set<Integer>> visited = new HashMap<>();

        while (!q.isEmpty()) {
            int[] cur = q.poll();
            int state = cur[0], node = cur[1];
            for (int next : graph[node]) {
                int nextState = state | (1 << next);
                if (nextState == all) {
                    return cur[2] + 1;
                }
                if (visited.containsKey(nextState) && visited.get(nextState).contains(next)) {
                    continue;
                }
                q.add(new int[]{nextState, next, cur[2] + 1});
                visited.computeIfAbsent(nextState, k -> new HashSet<>()).add(next);
            }
        }

        return 0;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant