Ada and Cycle

ADACYCLE - Ada and Cycle

no tags 

Ada the Ladybug is on a trip in Bugindia. There are many cities and some uni-directional roads connecting them. Ada is wondering about the shortest path, which begins in a city and ends in the same city. Since Ada likes short trips, she asked you to find the length of such path for each city in Bugindia.

Input

The first line will contain 0 < N ≤ 2000, the number of cities.

Then N lines follow, each containing N integers 0 ≤ Hij ≤ 1. One means, that there is a road between and (zero means there isn't a road).

Output

Print N lines, the length of shortest path which begins in city i and ends in city i. If the path doesn't exist, print "NO WAY" instead.

Example Input

5
0 1 1 1 1
1 0 0 0 1
0 0 1 1 0
0 0 1 0 0
0 0 0 1 0

Example Output

2
2
1
2
NO WAY

Example Input

5
0 1 0 0 1
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
1 0 0 0 0

Example Output

2
5
5
5
2

2.题意概述:

给你邻接矩阵,其中ij元素的0表示i到j没有道路,1表示有长度为1的道路,某人喜欢短途旅行,要你判断他在i城市时候的最短旅行路程是什么,不存在则输出NO WAY

3.解题思路

时间很宽松,因为每条边权值相同都为1,用最基础的bfs即可。


4.AC代码:


#include<bits/stdc++.h>
using namespace std;
const int N=2222;
const int inf=0x3f3f3f3f;
vector<int>vv[N];
bool vis[N];
int ans;
int n;
typedef pair<int,int> p;


int bfs(int i)
{
    queue<p>q;
    q.push(make_pair(0,i));

    while(!q.empty())
    {
        int top=q.front().second;
        int dis=q.front().first;
        q.pop();
        for(int j=0;j<vv[top].size();j++)
        {
            int tem=vv[top][j];
            if(!vis[tem])
            {
                vis[tem]=1;
                if(tem==i)
                    return  dis+1;
                    q.push(make_pair(dis+1,tem));
            }

        }
    }
    return inf;
}
int main()
{
    cin>>n;
    int tem;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            scanf("%d",&tem);
            if(tem)
            {
                vv[i].push_back(j);
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        ans=inf;
        if(vv[i].size())
        {
            memset(vis,false,sizeof(vis));
            ans=bfs(i);
        }
        if(ans==inf)
        {
            puts("NO WAY");
        }
        else
        {
            printf("%d\n",ans);
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值