zoukankan      html  css  js  c++  java
  • 847. Shortest Path Visiting All Nodes

    An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph.

    graph.length = N, and j != i is in the list graph[i] exactly once, if and only if nodes i and j are connected.

    Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

    Example 1:

    Input: [[1,2,3],[0],[0],[0]]
    Output: 4
    Explanation: One possible path is [1,0,2,0,3]

    Example 2:

    Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]
    Output: 4
    Explanation: One possible path is [0,1,4,2,3]

    Note:

    1. 1 <= graph.length <= 12
    2. 0 <= graph[i].length < graph.length

    Approach #1: BFS + Bit. [C++]

    class Solution {
    public:
        int shortestPathLength(vector<vector<int>>& graph) {
            const int n = graph.size();
            const int kAns = (1 << n) - 1;
            queue<pair<int, int>> q;
            vector<vector<int>> visited(n, vector<int>(1<<n));
            for (int i = 0; i < n; ++i) 
                q.push({i, 1 << i});
            int steps = 0;
            
            while (!q.empty()) {
                int s = q.size();
                while (s--) {
                    auto p = q.front();
                    q.pop();
                    int node = p.first;
                    int state = p.second;
                    if (state == kAns) return steps;
                    if (visited[node][state]) continue;
                    visited[node][state] = 1;
                    for (int next : graph[node])
                        q.push({next, state | (1 << next)});
                }
                ++steps;
            }
            
            return -1;
        }
    };
    

      

    Reference:

    http://zxi.mytechroad.com/blog/graph/leetcode-847-shortest-path-visiting-all-nodes/

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    第十周作业
    第九周编程作业与总结
    第八周编程作业及总结
    第七周编程总结
    第五周课程总结&试验报告(三)
    第四周课程总结&试验报告(二)
    第三周学习总结
    Java第二周学习总结
    2019年学习总结
    第十二周作业
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10581131.html
Copyright © 2011-2022 走看看