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 }

 

你可能感兴趣的:(Graph)