深度优先搜索DFS

来源:互联网 发布:网络摄像头哪个牌子好 编辑:程序博客网 时间:2024/05/01 13:37

例题引入

Description

I am a traveler. I want to post a letter to Merlin. But because there are so many roads I can walk through, and maybe I can’t go to Merlin’s house following these roads, I must judge whether I can post the letter to Merlin before starting my travel. 

Suppose the cities are numbered from 0 to N-1, I am at city 0, and Merlin is at city N-1. And there are M roads I can walk through, each of which connects two cities. Please note that each road is direct, i.e. a road from A to B does not indicate a road from B to A.

Please help me to find out whether I could go to Merlin’s house or not.

Input

There are multiple input cases. For one case, first are two lines of two integers N and M, (N<=200, M<=N*N/2), that means the number of citys and the number of roads. And Merlin stands at city N-1. After that, there are M lines. Each line contains two integers i and j, what means that there is a road from city i to city j.

The input is terminated by N=0.

Output

For each test case, if I can post the letter print “I can post the letter” in one line, otherwise print “I can't post the letter”.

Sample Input

320 11 2310 10

Sample Output

I can post the letterI can't post the letter
#include<iostream>#include<cstdio>using namespace std;const int MAXCITY=200;//记录是否访问过该城市 bool visited[MAXCITY];//邻接矩阵 int  matrix[MAXCITY][MAXCITY];int city,road;bool flag;void DFS(int currentCity,int count){ //代表0可以到达n-1城市  if(currentCity==city-1){ flag=true; return; } //城市遍历完,但是没找到到n-1的城市  else if(count==city){ flag=false; return; } else{ for(int i=0;i<city; i++){ if(!visited[i] && matrix[currentCity][i]==1){//没来过的城市,而有路  visited[i]=true; DFS(i,count+1); } } }}int main(){while(cin>>city>>road){for(int i=0;i<MAXCITY;i++)visited[i]=false;for(int i=0;i<MAXCITY;i++)for(int j=0;j<MAXCITY;j++)matrix[i][j]=0;int start,end;for(int i=0; i<road; i++){cin>>start>>end;matrix[start][end]=1;}flag=false;DFS(0,0);if(flag)  cout<<"I can post the letter"<<endl;else  cout<<"I can't post the letter"<<endl;}return 0;}


0 0