ALDS1_11_C Breadth First Search(邻接表转化为邻接矩阵并求每个点到1点的距离)

滴答滴答---题目链接 

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

Input

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

uu kk v1v1 v2v2 ... vkvk

uu is ID of the vertex and kk denotes its degree.vivi are IDs of vertices adjacent to uu.

Constraints

  • 1≤n≤1001≤n≤100

Output

For each vertex uu, print idid and dd in a line. idid is ID of vertex uuand dd is the distance from vertex 11 to vertex uu. If there are no path from vertex 11 to vertex uu, 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

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

#include<bits/stdc++.h>
using namespace std;
const int maxn=101;
const int inf=0x3f3f;
int e[maxn][maxn];
int vis[maxn],d[maxn],f[maxn],tt;
int n;
void bfs(int s)
{
    queue<int>q;
    q.push(s);
    for(int i=0; i<n; i++)
        d[i]=inf;
    d[s]=0;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(int v=0; v<n; v++)
        {
            if(e[u][v]==0)
                continue;
            if(d[v]!=inf)continue;
            d[v]=d[u]+1;
            q.push(v);
        }
    }
    for(int i=0; i<n; i++)
        cout<<i+1<<" "<<((d[i]==inf)?(-1):d[i])<<endl;
}
int main()
{
    int u,k,v;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
            e[i][j]=0;
    for(int i=0; i<n; i++)
    {
        scanf("%d%d",&u,&k);
        u--;
        for(int j=0; j<k; j++)
        {
            scanf("%d",&v);
            v--;
            e[u][v]=1;

        }
    }
    bfs(0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chen_zan_yu_/article/details/83818212