Sicily shortest path in unweighted graph

题目介绍:

输入一个无向图,指定一个顶点s开始bfs遍历,求出s到图中每个点的最短距离。

如果不存在s到t的路径,则记s到t的距离为-1。
 
Input

输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。

以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。 
 
Output

记s=1,在一行中依次输出:顶点1到s的最短距离,顶点2到s的最短距离,...,顶点n到s的最短距离。

每项输出之后加一个空格,包括最后一项。
 
Sample Input
5 3
1 2
1 3
2 4
Sample Output
0 1 1 2 -1 

思路:

     利用广度搜索,标记层数,依次计算距离即可。

     具体代码如下:

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 
 5 bool path[1001][1001];
 6 int shortest[1001];
 7 
 8 int main() {
 9     int n, m;
10     cin >> n >> m;
11     
12     for (int i = 1; i <= m; i++) {
13         int node1, node2;
14         cin >> node1 >> node2;
15         path[node1][node2] = true;
16         path[node2][node1] = true;
17     }
18     
19     for (int i = 1; i <= n; i++)
20         i == 1 ? shortest[i] = 0 : shortest[i] = -1;
21     
22     int distance = 0;
23     queue<int> store;
24     store.push(1);
25     while (!store.empty()) {
26         int size = store.size();
27         distance++;
28         while (size--) {
29             for (int i = 1; i <= n; i++) {
30                 if (path[store.front()][i] && shortest[i] == -1) {
31                     shortest[i] = distance;
32                     store.push(i);
33                 }
34             }
35             store.pop();
36         }
37     }
38     
39     for (int i = 1; i <= n; i++)
40         cout << shortest[i] << " ";
41     cout << endl;
42     
43     return 0;
44 }

 

转载于:https://www.cnblogs.com/winray/p/4152438.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值