鱼C论坛

 找回密码
 立即注册
查看: 3376|回复: 1

[技术交流] C++刷leetcode(847. 访问所有节点的最短路径)【状态压缩】【广度优先搜索】

[复制链接]
发表于 2021-3-3 17:29:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 给出 graph 为有 N 个节点(编号为 0, 1, 2, ..., N-1)的无向连通图。 

  2. graph.length = N,且只有节点 i 和 j 连通时,j != i 在列表 graph[i] 中恰好出现一次。

  3. 返回能够访问所有节点的最短路径的长度。你可以在任一节点开始和停止,也可以多次重访节点,并且可以重用边。

  4.  

  5. 示例 1:

  6. 输入:[[1,2,3],[0],[0],[0]]
  7. 输出:4
  8. 解释:一个可能的路径为 [1,0,2,0,3]
  9. 示例 2:

  10. 输入:[[1],[0,2,4],[1,3,4],[2],[1,2]]
  11. 输出:4
  12. 解释:一个可能的路径为 [0,1,4,2,3]
  13.  

  14. 提示:

  15. 1 <= graph.length <= 12
  16. 0 <= graph[i].length <&#160;graph.length

  17. 来源:力扣(LeetCode)
  18. 链接:https://leetcode-cn.com/problems/shortest-path-visiting-all-nodes
  19. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码



  1. class Solution {
  2. private:
  3.     struct State{
  4.         int visited_state;
  5.         int cur_index;
  6.         State(int visited_state, int cur_index): visited_state(visited_state), cur_index(cur_index){}
  7.     };
  8. public:
  9.     int shortestPathLength(vector<vector<int>>& graph) {
  10.         int N = graph.size();
  11.         vector<vector<bool> >store_state(1 << N, vector<bool>(N, false));//N个节点共有2^N个状态
  12.         //确定结束状态
  13.         int end = (1 << N) - 1;
  14.         queue<State> store;
  15.         //分别以每个节点为初始点,开始遍历
  16.         for(int i = 0; i < N; i++){
  17.             State cur(1 << i, i);
  18.             store.push(cur);
  19.         }
  20.         //广度优先搜索
  21.         int res = 0;
  22.         while(!store.empty()){
  23.             int temp = store.size();
  24.             for(int i = 0; i < temp; i++){
  25.                 State temp1 = store.front();
  26.                 store.pop();
  27.                 int visit = temp1.visited_state;
  28.                 int cur = temp1.cur_index;
  29.                 if(visit == end){
  30.                     return res;
  31.                 }
  32.                 for(auto next_index : graph[cur]){
  33.                     int next_visited = (visit | (1 << next_index));
  34.                     if(store_state[next_visited][next_index] == false){
  35.                         store.push(State(next_visited, next_index));
  36.                         store_state[next_visited][next_index] = true;
  37.                     }
  38.                 }
  39.             }
  40.             res++;
  41.         }
  42.         return -1;
  43.     }
  44. };
复制代码




状态压缩参考:https://www.bilibili.com/video/B ... 5698129737800543270
代码参考:https://leetcode-cn.com/problems ... -suo-by-hardcoding/

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-3-3 17:29:41 | 显示全部楼层
过年后就好久没发帖了学起来!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-6 21:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表