1005. shortest path in unweighted graph

题目

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值