http://ybt.ssoier.cn:8088/problem_show.php?pid=1215
1215:迷宫时间限制: 1000 ms 内存限制: 65536 KB 提交数: 37906 通过数: 11425 【题目描述】一天Extense在森林里探险的时候不小心走入了一个迷宫,迷宫可以看成是由n×nn×n的格点组成,每个格点只有22种状态, 【输入】第1行是测试数据的组数kk,后面跟着kk组输入。每组测试数据的第11行是一个正整数n(1≤n≤100)n(1≤n≤100),表示迷宫的规模是n×nn×n的。接下来是一个n×nn×n的矩阵,矩阵中的元素为 【输出】kk行,每行输出对应一个输入。能办到则输出“YES”,否则输出“NO”。 【输入样例】2
3
.##
..#
#..
0 0 2 2
5
.....
###.#
..#..
###..
...#.
0 0 4 0 【输出样例】YES
NO |
对于这类连通型迷宫问题,dfs和bfs都可以解决,但是dfs相对来说代码量更少,速度更快一点,但是bfs可以找到最短路径
dfs
#include<bits/stdc++.h>
#include<vector>
using namespace std;
bool flag[105][105];
string st[105];
int n;
int ha,la,hb,lb;
int a[]={1,-1,0,0};
int b[]={0,0,1,-1};
int t;
/*
对于dfs函数,最好写成bool类型,相对于void类型来说,效率更高一点,避免了超市的错误
最初,我就是写的void类型,但是超时了,看了一些大佬的代码,发现改成bool类型之后,时间复杂度明显降低了很多,轻松AC
*/
bool dfs(int x,int y){
// cout<<"&&&"<<endl;
flag[x][y]=true;
if(x==hb&&y==lb){
cout<<"YES"<<endl;
return true;
}
for(int i=0;i<4;i++){
int xx=x+a[i];
int yy=y+b[i];
if(xx<0||xx>=n||yy<0||yy>=n) continue;
if(st[xx][yy]=='#'||flag[xx][yy]) continue;
if(dfs(xx,yy)) return true;
/*
这步是 降低时间复杂度的关键,具体说不上来为什么,记住就行
*/
}
return false;
}
int main(){
int k;
scanf("%d",&k);
while(k--){
scanf("%d",&n);
for(int i=0;i<n;i++){
cin>>st[i];
}
memset(flag,false,sizeof(flag));
scanf("%d %d %d %d",&ha,&la,&hb,&lb);
if(st[ha][la]=='#'||st[hb][lb]=='#'){
cout<<"NO"<<endl;
continue;
}
if(!dfs(ha,la))
cout<<"NO"<<endl;
}
return 0;
}
bfs
#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<string>
using namespace std;
int k;
int n;
int ha,la,hb,lb;
int a[]={1,-1,0,0};
int b[]={0,0,1,-1};
struct node{
int x1;
int y1;
};
bool flag[105][105];
string st[105];
void bfs(int x,int y){
queue<node> qu;
flag[x][y]=true;
qu.push(node{x,y});
while(!qu.empty()){
node now=qu.front();
qu.pop();
if(now.x1==hb&&now.y1==lb){
cout<<"YES"<<endl;
return ;
}
for(int i=0;i<4;i++){
int xx=now.x1+a[i];
int yy=now.y1+b[i];
if(xx<0||xx>=n||yy<0||yy>=n) continue;
if(st[xx][yy]=='#'||flag[xx][yy]) continue;
qu.push(node{xx,yy});
flag[xx][yy]=true;
}
}
cout<<"NO"<<endl;
return ;
}
int main(){
cin>>k;
while(k--){
cin>>n;
for(int i=0;i<n;i++){
cin>>st[i];
}
cin>>ha>>la>>hb>>lb;
memset(flag,false,sizeof(flag));
if(st[ha][la]=='#'||st[hb][lb]=='#'){
cout<<"NO"<<endl;
continue;
}
bfs(ha,la);
}
return 0;
}