二Day1A - Breadth First Search

本文介绍了使用Breadth First Search(BFS)算法解决从顶点1到图中所有顶点的最短距离问题。提供了输入输出示例及代码实现,并对BFS算法进行了简单总结。
摘要由CSDN通过智能技术生成

二Day1A - Breadth First Search

题目正文

Write a program which reads an directed graph G=(V,E), and finds the shortest distance from vertex 1 to each vertex (the number of edges in the shortest path). Vertices are identified by IDs 1,2,…n.

Input
In the first line, an integer n denoting the number of vertices, is given. In the next n lines, adjacent lists of vertex u are given in the following format:

u k v1 v2 … vk

u is ID of the vertex and k denotes its degree.vi are IDs of vertices adjacent to u.

Constraints
1≤n≤100
Output
For each vertex u, print id and d in a line. id is ID of vertex u and d is the distance from vertex 1 to vertex u. If there are no path from vertex 1 to vertex u, print -1 as the shortest distance. Print in order of IDs.

Sample Input 1
4
1 2 2 4
2 1 4
3 0
4 1 3
Sample Output 1
1 0
2 1
3 2
4 1

代码

代码:

//1.定义最大值maxn,定义一个无穷大的数0x3f3f,设置一个二维数组,一个一维数组
//2.bfs()函数中传入参数,定义一个队列,s进队列,循环,一维数组的每个值设置为无穷大
//3.while循环q队列不为空,定义队首指针,并出队列,for循环,遍历相邻顶点
//4.如果邻接矩阵的顶点为零,跳出,如果顶点不为无穷跳出,否则,相邻顶点加1,进队列
//5.循环输出,是否为inf,是,输出-1,否则输出该顶点的数
//6.主函数里,,定义N,输入n,两层循环二维数组为0,两层循环输入u,k,u--
//7.第二层循环输入v,v--;e[u][v]=1,调用bfs()
#include<stdio.h>
#include<queue>
#include<iostream>
using namespace std;
const int maxn=50;
const int inf=
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值