sicily 1155 Can I Post the letter

时间:2022-05-10 05:04:13

题意:判断有向图两点之间是否可通达!

解法:深搜或广搜(注意避免旧路重行)

  

   DFS:

 #include<iostream>
#include<vector>
#include<string.h>
using namespace std; struct Road{
int From;
int Dest;
bool Vist;
Road(int f,int d,bool v){
From = f;
Dest = d;
Vist = v;
}
};
vector<Road> roads[];
bool reach=false;
int N,M; void dfs(int n){
if(n == N-){
reach = true;
return;
}
for(int i=;i<roads[n].size();i++){
if(roads[n][i].Vist && roads[n][i].Dest !=){
int gonext =roads[n][i].Dest;
//use to avoid repeat search
roads[n][i].Vist = false;
dfs(gonext);
}
}
}
int main(){
while(cin>>N && N>){
cin>>M;
reach = false;
memset(roads,,sizeof(roads));
int from,dest;
bool exist = true;
for(int i=;i<M;i++){
cin >> from>>dest;
Road r = Road(from,dest,exist);
roads[from].push_back(r);
}
//deep search
dfs();
if(reach){
cout<<"I can post the letter"<<endl;
}
else{
cout<<"I can't post the letter"<<endl;
}
}
return ;
}

BFS:

 #include<iostream>
#include<string.h>
#include<queue>
using namespace std; int N,M;
int roads[][];
bool visited[]; int main(){
while(cin>>N && N>){
cin>>M;
memset(roads,,sizeof(roads));
memset(visited,false,sizeof(visited));
int from=,dest=;
for(int i=;i<M;i++){
cin >> from>>dest;
roads[from][dest] = ;
}
//breadth-first search
queue<int> que;
que.push();
int i;
while(!que.empty() && visited[N-] !=true){
i = que.front();
for(int j=;j<N;j++){
if(roads[i][j] == && visited[j] == false)
{
visited[j] = true;
que.push(j);
}
}
que.pop();
}
if(visited[N-] == true){
cout<<"I can post the letter"<<endl;
}
else{
cout<<"I can't post the letter"<<endl;
}
}
return ;
}