题面
一天Extense在森林里探险的时候不小心走入了一个迷宫,迷宫可以看成是由 n×n 的格点组成,每个格点只有 22 种状态, 00 和 11,前者表示可以通行后者表示不能通行。
同时当Extense处在某个格点时,他只能移动到东南西北(或者说上下左右)四个方向之一的相邻格点上,Extense想要从点 A 走到点 B ,问在不走出迷宫的情况下能不能办到。
如果起点或者终点有一个不能通行(为 1),则看成无法办到。
输入
第 1 行是一个正整数 n (1≤n≤100),表示迷宫的规模是 n×n 的。
接下来是一个 n×n 的矩阵,矩阵中的元素为 0 或者 1。
再接下来一行是 4 个整数 ha la hb lb,描述 A 处在第ha 行 第 la 列,B 处在第hb 行 第 lb 列。
输出
能办到则输出 YES
,否则输出 NO
。
样例
输入
3
0 1 1
0 0 1
1 0 0
1 1 3 3
输出
典中典中典的dfs或bfs题,用dfs做的话要注意边界和到没到达终点。
解法一:到了终点用一个f来标记,true就是到了,false就反之
#include <bits/stdc++.h>
using namespace std;
int a[110][110];
int n , s1 , s2 , e1 , e2;
bool f = false;
int fx[5] = {0 , 0 , 1 , 0 , -1};
int fy[5] = {0 , 1 , 0 , -1 , 0};
void dfs(int x , int y){
a[x][y] = 1;
int tx , ty;
for ( int i = 1 ; i <= 4 ; i++ ){
tx = x + fx[i];
ty = y + fy[i];
if(tx >= 1 && tx <= n && ty >= 1 && ty <= n && a[tx][ty] == 0 ){
if(tx == e1 && ty == e2) f = true;
else dfs(tx , ty);
}
}
}
int main(){
scanf("%d" , &n);
for ( int i = 1 ; i <= n ; i++ )
for ( int j = 1 ; j <= n ; j++ )
scanf("%d" , &a[i][j]);
scanf("%d%d%d%d" , &s1 , &s2 , &e1 , &e2);
if ( a[s1][s2] == 1 || a[e1][e2] == 1 )
printf("NO");
else{
dfs(s1 , s2);
if ( f == true )
printf("YES");
else
printf("NO");
}
return 0;
}
解法二:多加了一个判断条件f==false,这能防止无效递归
#include <bits/stdc++.h>
using namespace std;
int a[110][110];
int n , s1 , s2 , e1 , e2;
bool f = false;
int fx[5] = {0 , 0 , 1 , 0 , -1};
int fy[5] = {0 , 1 , 0 , -1 , 0};
void dfs(int x , int y){
a[x][y] = 1;
int tx , ty;
for ( int i = 1 ; i <= 4 ; i++ ){
tx = x + fx[i];
ty = y + fy[i];
if(tx >= 1 && tx <= n && ty >= 1 && ty <= n && a[tx][ty] == 0 && f == false){
if(tx == e1 && ty == e2) f = true;
else dfs(tx , ty);
}
}
}
int main(){
scanf("%d" , &n);
for ( int i = 1 ; i <= n ; i++ )
for ( int j = 1 ; j <= n ; j++ )
scanf("%d" , &a[i][j]);
scanf("%d%d%d%d" , &s1 , &s2 , &e1 , &e2);
if ( a[s1][s2] == 1 || a[e1][e2] == 1 )
printf("NO");
else{
dfs(s1 , s2);
if ( f == true )
printf("YES\n");
else
printf("NO");
}
return 0;
}
解法三:到了终点直接输出YES,然后结束整个程序
#include <bits/stdc++.h>
using namespace std;
int a[110][110];
int n , s1 , s2 , e1 , e2;
int fx[5] = {0 , 0 , 1 , 0 , -1};
int fy[5] = {0 , 1 , 0 , -1 , 0};
void dfs(int x , int y){
a[x][y] = 1;
int tx , ty;
for ( int i = 1 ; i <= 4 ; i++ ){
tx = x + fx[i];
ty = y + fy[i];
if(tx >= 1 && tx <= n && ty >= 1 && ty <= n && a[tx][ty] == 0 ){
if(tx == e1 && ty == e2) {
printf("YES");
exit(0); //Í£Ö¹³ÌÐò
}
else dfs(tx , ty);
}
}
}
int main(){
scanf("%d" , &n);
for ( int i = 1 ; i <= n ; i++ )
for ( int j = 1 ; j <= n ; j++ )
scanf("%d" , &a[i][j]);
scanf("%d%d%d%d" , &s1 , &s2 , &e1 , &e2);
if ( a[s1][s2] == 1 || a[e1][e2] == 1 )
printf("NO");
else{
dfs(s1 , s2);
printf("NO");
}
return 0;
}