您的位置:首页 > 其它

hdu 1307 N-Credible Mazes

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

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

#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<set>
#include<map>
using namespace std;
int st,ed;
map<int,vector<int> >Map;
set<int>Set;
int n;
bool Input(int &num,int n){
num=0;
int x;
for(int i=1;i<=n;i++){
scanf("%d",&x);
if(x==-1)return false;
num=num*10+x;
}
return true;
}

bool dfs(int st,int ed){
if(st==ed)return true;
for(int i=0;i<Map[st].size();i++){
int v=Map[st][i];
//只能返回0或1,1表示该数已经插入
if(!Set.count(v)){
Set.insert(v);
if(dfs(v,ed))return true;
}
}
return false;
}

int main(){
int x,t=1;
while(scanf("%d",&n),n){
Map.clear(),Set.clear();
Input(st,n);
Input(ed,n);
int s,e;
while(Input(s,n)){
Input(e,n);
Map[s].push_back(e);
Map[e].push_back(s);
}
if(dfs(st,ed)){
printf("Maze #%d can be travelled\n",t++);
}else
printf("Maze #%d cannot be travelled\n",t++);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: