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的最短距离。
每项输出之后加一个空格,包括最后一项。
================================================================
先贴代码:
// Problem#: 4376
// Submission#: 1455794
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<iostream>
#include<queue>
using namespace std;
int a[1005][1005] , res[1005];
bool visited[1005];
int n,m;
void bfs()
{
queue<int> que;
que.push(1);
visited[1] = 1;
res[1] = 0;
while(!que.empty())
{
int now = que.front();
que.pop();
for(int i = 1; i <=n; i++)
{
if(a[now][i] && !visited[i])
{
res[i] = res[now] + 1;
visited[i] = 1;
que.push(i);
}
}
}
}
int main()
{
cin>>n>>m;
for(int i = 0;i < m;i++)
{
int tmp1,tmp2;
cin>>tmp1>>tmp2;
a[tmp1][tmp2] = a[tmp2][tmp1] = 1;
}
for(int i = 1; i<=n ; i++)
{
res[i] = -1;
}
bfs();
for(int i = 1 ; i <= n; i++)
{
cout<<res[i]<<" ";
}
cout<<endl;
//system("pause");
}
离考试还有三天,开始学习图算法。补去年数据结构的课。
第一题是关于无权无向图的广搜。
用了bfs
从第一个数开始搜,将其放入队列que,然后搜有边的点,每搜到一个点将其push进队列,同时置visited[i]为1;
因为是无权图,所以第一次搜到的肯定是最短的。
于是每次要跳过visited为1的点
还要注意的一点是无向图中,a[x][y] = a[y][x] = 1;
keep moving.
我起步晚,但我不怕晚。