Sicily shortest path in unweighted graph

For study!

Posted by Winray on March 4, 2016
  • 题目介绍:
输入一个无向图,指定一个顶点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 
  • 思路:
    • 利用广度搜索,标记层数,依次计算距离即可。
  • 具体代码如下:
#include <iostream>
#include <queue>
using namespace std;

bool path[1001][1001];
int shortest[1001];

int main() {
    int n, m;
    cin >> n >> m;
    
    for (int i = 1; i <= m; i++) {
        int node1, node2;
        cin >> node1 >> node2;
        path[node1][node2] = true;
        path[node2][node1] = true;
    }
    
    for (int i = 1; i <= n; i++)
        i == 1 ? shortest[i] = 0 : shortest[i] = -1;
    
    int distance = 0;
    queue<int> store;
    store.push(1);
    while (!store.empty()) {
        int size = store.size();
        distance++;
        while (size--) {
            for (int i = 1; i <= n; i++) {
                if (path[store.front()][i] && shortest[i] == -1) {
                    shortest[i] = distance;
                    store.push(i);
                }
            }
            store.pop();
        }
    }
    
    for (int i = 1; i <= n; i++)
        cout << shortest[i] << " ";
    cout << endl;
    
    return 0;
}