shortest path in unweighted graph

Description

输入一个无向图,指定一个顶点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
 Copy sample input to clipboard
5 3
1 2
1 3
2 4
Sample Output
0 1 1 2 -1 

 

 
   

 

View Code
 1 #include <iostream>
 2 #include <vector>
 3 #include <cstring>
 4 #include <queue>
 5 using namespace std;
 6 
 7 int n, m;
 8 vector<int>v[1002];
 9 bool visited[1002];
10 int dis[1002];
11 void bfs()
12 {
13     memset(visited, false, sizeof(visited));
14     memset(dis, 0, sizeof(dis));
15     queue<int>q;
16     q.push(1);
17     visited[1] = true;
18     while (!q.empty()){
19         int a = q.front();
20         q.pop();
21         
22         int size = v[a].size();
23         for (int i = 0; i < size; i++){
24             int b = v[a][i];
25             if (!visited[b]){
26                dis[b] = dis[a] + 1;
27                q.push(b);
28                visited[b] = true;   
29             }
30         }
31     }
32 }
33 
34 int main()
35 {
36     int a, b;
37     cin >> n >> m;
38     
39     for (int i = 0; i < m; i++){
40         cin >> a >> b;
41         v[a].push_back(b);
42         v[b].push_back(a);
43     }
44     bfs();
45     cout << 0 << " ";
46     for (int i = 2; i <= n; i++)
47         if (dis[i] == 0)
48            cout << -1 << " ";
49         else
50            cout  << dis[i] << " ";
51     cout << endl;
52     //system("PAUSE");
53     return 0;
54 }                                 

 

posted @ 2012-12-22 13:34  gumcstronger  阅读(260)  评论(0)    收藏  举报