Sicily 1155 Can I Post the letter (图的遍历 BFS)

题目:http://soj.me/1155

   n座城市 m条道路 问能否从第一座城市走到最后一座城市

思路:广度优先搜索

#include <iostream>
#include <queue>
#include <memory.h>
using namespace std;

bool map[205][205];
bool visit[205];
int n,m;

bool bfs()
{
    queue<int> q;
    q.push(0);
    
    while(!q.empty())
    {
        int temp=q.front();
        q.pop();
        for(int i=0;i<n;i++)
        {
            if(map[temp][i]==1&&visit[i]==0)
            {
                if(i==n-1) return 1;
                q.push(i);
                visit[i]=1;
                
            }
        }
    }
    return 0;

}

int main()
{
    while(1)
    {
        memset(map,0,sizeof(map));
        memset(visit,0,sizeof(visit));
        cin>>n>>m;
        if(!n) break;
        for (int i = 0; i < m; i++)
        {
            int a,b;
            cin>>a>>b;
            map[a][b]=1;
        }
        bool ans=bfs();
        if(ans) cout<<"I can post the letter"<<endl;
        else cout<<"I can't post the letter"<<endl;
    }
    return 0;
}

 

posted @ 2013-01-30 11:27  Daniel Qiu  阅读(281)  评论(0编辑  收藏  举报