Sicily shortest path in unweighted graph, sicilyunweighted
Topic introduction:
Enter an undirected graph, specify a vertex s to start bfs traversal, and obtain the shortest distance from s to each vertex in the graph.
If the path from s to t does not exist, the distance from s to t is-1. Input
The first line of the input contains two integers n and m. n indicates the number of vertices of the graph, and m indicates the number of edges. 1 <= n <= 1000,0 <= m <= 10000.
In the following m rows, each row is a number pair v y, indicating that an edge (v, y) exists ). Vertex number starts from 1. Output
Note s = 1, and output in one row: the shortest distance from vertex 1 to vertex s, the shortest distance from vertex 2 to vertex s,..., the shortest distance from vertex n to vertex s.
Add a space after each output, including the last one. Sample Input
5 31 21 32 4
Sample Output
0 1 1 2 -1
Ideas:
Use the breadth search function to mark the number of layers and calculate the distance in sequence.
The Code is as follows:
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 }