2014.07.04 18:24
简介:
给定一个有向图,你可以认为每条边长度都是1(所以叫无权值)。下面的算法可以求出从特定的起点到终点的最短路径长度。
描述:
从起点出发,根据当前顶点出发的边进行广度优先搜索,直至找到终点即可。如果搜索结束了仍然没有找到终点,那么起点无法到达终点。
实现:
1 // A simple illustration for unweighted shortest path. Graph represented by adjacency matrix. 2 #include <iostream> 3 #include <queue> 4 #include <vector> 5 using namespace std; 6 7 void unweightedShortestPath(const vector<vector<bool> > &graph, 8 vector<int> &dist, vector<bool> &reachable) 9 { 10 // The minimal distances from 0th vertex to others. 11 int n; 12 int i, j; 13 14 n = (int)graph.size(); 15 dist.resize(n); 16 reachable.resize(n); 17 18 if (n < 1) { 19 return; 20 } 21 22 for (i = 0; i < n; ++i) { 23 reachable[i] = false; 24 } 25 26 queue<int> q; 27 28 dist[0] = 0; 29 reachable[0] = true; 30 31 q.push(0); 32 while (!q.empty()) { 33 i = q.front(); 34 q.pop(); 35 for (j = 0; j < n; ++j) { 36 if (!graph[i][j] || reachable[j]) { 37 continue; 38 } 39 dist[j] = dist[i] + 1; 40 reachable[j] = true; 41 q.push(j); 42 } 43 } 44 } 45 46 int main() 47 { 48 vector<vector<bool> > graph; 49 vector<int> dist; 50 vector<bool> reachable; 51 int n; 52 int nk; 53 int i, j; 54 int tmp; 55 56 while (cin >> n && n > 0) { 57 graph.resize(n); 58 for (i = 0; i < n; ++i) { 59 graph[i].resize(n, false); 60 } 61 62 for (i = 0; i < n; ++i) { 63 cin >> nk; 64 for (j = 0; j < nk; ++j) { 65 cin >> tmp; 66 graph[i][tmp] = true; 67 } 68 } 69 70 unweightedShortestPath(graph, dist, reachable); 71 72 for (i = 0; i < n; ++i) { 73 cout << i << ": "; 74 if (reachable[i]) { 75 cout << dist[i] << endl; 76 } else { 77 cout << "Unreachable" << endl; 78 } 79 } 80 81 for (i = 0; i < n; ++i) { 82 graph[i].clear(); 83 } 84 graph.clear(); 85 } 86 87 return 0; 88 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)