zoukankan      html  css  js  c++  java
  • hdu 1307

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1307

    先说一下题意,就是给你n维起始点和终点的坐标,然后后面给出一系列的点,每一行表示这两个点之间有通路,最后让你判断一下能否从起点出发走到终点。

    由于最多不超过10维,那么我们把每个点的坐标转化为一个整数,然后建邻接表,这样dfs就可以了(值得注意的是我们用set来判重,当然你也可以用数组什么的)

    可以说是dfs+map+set的妙用了!

    View Code
     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cmath>
     4 #include<vector>
     5 #include<set>
     6 #include<map>
     7 using namespace std;
     8 int st,ed;
     9 map<int,vector<int> >Map;
    10 set<int>Set;
    11 int n;
    12 bool Input(int &num,int n){
    13     num=0;
    14     int x;
    15     for(int i=1;i<=n;i++){
    16         scanf("%d",&x);
    17         if(x==-1)return false;
    18         num=num*10+x;
    19     }
    20     return true;
    21 }
    22 
    23 bool dfs(int st,int ed){
    24     if(st==ed)return true;
    25     for(int i=0;i<Map[st].size();i++){
    26         int v=Map[st][i];
    27         //只能返回0或1,1表示该数已经插入
    28         if(!Set.count(v)){
    29             Set.insert(v);
    30             if(dfs(v,ed))return true;
    31         }
    32     }
    33     return false;
    34 }
    35 
    36 
    37 int main(){
    38     int x,t=1;
    39     while(scanf("%d",&n),n){
    40         Map.clear(),Set.clear();
    41         Input(st,n);
    42         Input(ed,n);
    43         int s,e;
    44         while(Input(s,n)){
    45             Input(e,n);
    46             Map[s].push_back(e);
    47             Map[e].push_back(s);
    48         }
    49         if(dfs(st,ed)){
    50             printf("Maze #%d can be travelled\n",t++);
    51         }else 
    52             printf("Maze #%d cannot be travelled\n",t++);
    53     }
    54     return 0;
    55 }
    56 
    57 
    58 
    59     
  • 相关阅读:
    爱摘苹果的小明
    盗梦空间
    九九乘法表
    谁是最好的Coder
    画图
    黑色帽子
    a letter and a number
    运维开发面试题
    python 守护进程daemon
    kubernets 应用部署
  • 原文地址:https://www.cnblogs.com/wally/p/3074602.html
Copyright © 2011-2022 走看看