meifan666 @ 2024-07-10 20:09:47
#include<bits/stdc++.h>
using namespace std;
int n,m;
bool b;
char a[120][120];
bool flag[120][120];
void DFS(int x,int y){
flag[x][y]=1;
// printf("%d %d\n",x,y);
if(x==n&&y==m){
b=1;
return;
}
if(x!=n&&a[x+1][y]!='#'&&!flag[x+1][y]){
DFS(x+1,y);
}
if(x!=1&&a[x-1][y]!='#'&&!flag[x-1][y]){
DFS(x-1,y);
}
if(y!=m&&a[x][y+1]!='#'&&!flag[x][y+1]){
DFS(x,y+1);
}
if(y!=1&&a[x][y-1]!='#'&&!flag[x][y-1]){
DFS(x,y-1);
}
flag[x][y]=0;
return;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
DFS(1,1);
if(b)printf("Yes");
else{
printf("No");
}
return 0;
}
by meifan666 @ 2024-07-10 20:10:47
连递归都不会,刚自学DFS,神犇轻点喷
by keep_shining @ 2024-07-10 20:30:30
@meifan666
#include<bits/stdc++.h>
using namespace std;
int n,m;
bool b;
char a[120][120];
bool flag[120][120];
void DFS(int x,int y){
flag[x][y]=1;
// printf("%d %d\n",x,y);
if(x==n&&y==m){
b=1;
return;
}
if(x!=n&&a[x+1][y]!='#'&&!flag[x+1][y]){
DFS(x+1,y);
}
if(x!=1&&a[x-1][y]!='#'&&!flag[x-1][y]){
DFS(x-1,y);
}
if(y!=m&&a[x][y+1]!='#'&&!flag[x][y+1]){
DFS(x,y+1);
}
if(y!=1&&a[x][y-1]!='#'&&!flag[x][y-1]){
DFS(x,y-1);
}
//flag[x][y]=0;
//这句不需要,只要不是求方案数,就不用回溯
return;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
DFS(1,1);
if(b)printf("Yes");
else{
printf("No");
}
return 0;
}
by keep_shining @ 2024-07-10 20:30:59
@meifan666 求关
by meifan666 @ 2024-07-10 20:42:47
@keep_shining 感谢大佬,已关