首页 > 其他 > 详细

847. Shortest Path Visiting All Nodes

时间:2019-03-22 21:55:48      阅读:219      评论:0      收藏:0      [点我收藏+]

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/

 

847. Shortest Path Visiting All Nodes

原文:https://www.cnblogs.com/ruruozhenhao/p/10581131.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!