sicily 1155 Can I Post the letter

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

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

  

   DFS:

 1 #include<iostream>
 2 #include<vector>
 3 #include<string.h>
 4 using namespace std;
 5 
 6 struct Road{
 7     int From;
 8     int Dest;
 9     bool Vist;
10     Road(int f,int d,bool v){
11         From = f;
12         Dest = d;
13         Vist = v;
14     }
15 };
16 vector<Road> roads[20001];
17 bool reach=false;
18 int N,M;
19 
20 void dfs(int n){
21     if(n == N-1){
22         reach = true;
23         return;
24     }
25     for(int i=0;i<roads[n].size();i++){
26         if(roads[n][i].Vist && roads[n][i].Dest !=0){
27             int gonext =roads[n][i].Dest;
28             //use to avoid repeat search
29             roads[n][i].Vist = false;    
30             dfs(gonext);
31         }
32     }
33 }
34 int main(){
35     while(cin>>N && N>0){
36         cin>>M;
37         reach = false;
38         memset(roads,0,sizeof(roads));
39         int from,dest;
40         bool exist = true;
41         for(int i=0;i<M;i++){
42             cin >> from>>dest;
43             Road r = Road(from,dest,exist);
44             roads[from].push_back(r);
45         }
46         //deep search
47         dfs(0);
48         if(reach){
49             cout<<"I can post the letter"<<endl;
50         }
51         else{
52             cout<<"I can't post the letter"<<endl;
53         }
54     }
55     return 0;
56 }

       BFS:

 1 #include<iostream>
 2 #include<string.h>
 3 #include<queue>
 4 using namespace std;
 5 
 6 int N,M;
 7 int roads[201][201];
 8 bool visited[200001];
 9 
10 int main(){
11     while(cin>>N && N>0){
12         cin>>M;
13         memset(roads,0,sizeof(roads));
14         memset(visited,false,sizeof(visited));
15         int from=0,dest=0;
16         for(int i=0;i<M;i++){
17             cin >> from>>dest;
18             roads[from][dest] = 1;
19         }
20         //breadth-first search
21         queue<int> que;
22         que.push(0);
23         int i;
24         while(!que.empty() && visited[N-1] !=true){
25             i = que.front();
26             for(int j=0;j<N;j++){
27                 if(roads[i][j] == 1 && visited[j] == false)
28                 {
29                     visited[j] = true;
30                     que.push(j);
31                 }
32             }
33             que.pop();
34         }
35         if(visited[N-1] == true){
36             cout<<"I can post the letter"<<endl;
37         }
38         else{
39             cout<<"I can't post the letter"<<endl;
40         }
41     }
42     return 0;
43 }

 

 

转载于:https://www.cnblogs.com/renaissance/p/3512831.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值