题目
Time Limit: 1sec Memory Limit:256MB
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
5 3
1 2
1 3
2 4
Sample Output Copy
0 1 1 2 -1
Problem Source: 刘晓铭
学习
参考:https://blog.csdn.net/changyuanchn/article/details/17077379
有向图算法推导
思路:从3开始,使3入队,找3的邻接点1,6,故s[1] = s[6] = 1,
1, 6入队,找1的邻接点为2,4,6没有邻接点,取消。故s[2] = s[4] = 2,
2,4入队,找2的邻接点为4(之前访问过,取消),4 的邻接点为3(取消),5,6(取消),7 .故s[5] = s[7] = 3
...
伪代码:
int dist = 0, queue q.
起始元素入队
while(q非空)
{
int count = q.size()//q中多个元素,属于同一级
dist++//每一批次的dist逐渐增加
while(count--)
{
q.front();
//第1,2...个队首元素,寻找邻接点
遍历所有顶点,找到邻接点j, j入队 ,s[j] = dist;
q.pop();
}
}
*/
code
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int vers, edges;
bool matrix[1001][1001];
bool isVisited[1001];
int shortest[1001];
int main()
{
cin >> vers >> edges;
memset(matrix, false, 1001 * 1001 *sizeof(bool));
memset(isVisited, false, 1001 * sizeof(bool));
memset(shortest, -1, 1001 * sizeof(int));
for(int i = 0; i < edges; ++i)
{
int a, b;
cin >> a >> b;
matrix[a][b] = matrix[b][a] = true;
}
queue<int> q;
int dist = 0;
q.push(1);
shortest[1] = dist;
isVisited[1] = true;
while(!q.empty())
{
int count = q.size();
dist++;
while(count--)
{
int front = q.front();
q.pop();
for(int i = 1; i <= vers; ++i)
{
if(matrix[front][i] && (!isVisited[i]))
{
q.push(i);
shortest[i] = dist;
isVisited[i] = true;
}
}
}
}
for(int i = 1; i <= vers; ++i)
{
cout << shortest[i] << " ";
}
cout << endl;
return 0;
}