laozhang_123 @ 2024-08-18 20:04:23
用dfsT了,用bfsM了,今天真是倒大霉了
DFS:
#include<bits/stdc++.h>
using namespace std;
bool io=0;
char mp[110][110];
int n,m,dx[5]={0,0,0,1,-1},dy[5]={0,1,-1,0,0};
bool ext(int ex,int ey){
if(ex<1&&ex>n&&ey<1&&ey>m) return 0;
return 1;
}
void dfs(int x,int y){
if(x==n&&y==m){
io=1;
return ;
}
for(int i=1;i<=4;i++){
int wx=x+dx[i],wy=y+dy[i];
if(ext(wx,wy)&&mp[wx][wy]=='.'){
mp[wx][wy]='#';
dfs(wx,wy);
mp[wx][wy]='.';
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>mp[i][j];
}
}
dfs(1,1);
if(io==1) cout<<"Yes";
else cout<<"No";
return 0;
}
BFS:
#include<bits/stdc++.h>
using namespace std;
bool io=0;
char mp[110][110];
int n,m,dx[5]={0,0,0,1,-1},dy[5]={0,1,-1,0,0};
struct Pos{int x,y;};
bool ext(int ex,int ey){
if(ex<1&&ex>n&&ey<1&&ey>m) return 0;
return 1;
}
void bfs(){
queue<Pos> que;
Pos fp; fp.x=1,fp.y=1;
que.push(fp);
while(!que.empty()){
Pos np=que.front();
que.pop();
if(np.x==n&&np.y==m){
io=1;
return ;
}
for(int i=1;i<=4;i++){
int wx=np.x+dx[i],wy=np.y+dy[i];
if(ext(wx,wy)&&mp[wx][wy]=='.'){
mp[np.x][np.y]='#';
Pos wp; wp.x=wx,wp.y=wy;
que.push(wp);
mp[np.x][np.y]='.';
}
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>mp[i][j];
}
}
bfs();
if(io==1) cout<<"Yes";
else cout<<"No";
return 0;
}
by huangshuchang @ 2024-08-18 20:11:21
@laozhang_123 求关注
#include <bits/stdc++.h>
#define int long long
using namespace std;
int dx[]={0,-1,1,0};
int dy[]={-1,0,0,1};
char a[105][105];
bool vis[105][105];
int n,m;
bool dfs(int i,int j){
if (!i||!j||i>n||j>m||a[i][j]=='#'||vis[i][j]) return false;
if (i==n&&j==m) return true;
vis[i][j]=1;
for (int k=0;k<4;k++){
if (dfs(i+dx[k],j+dy[k])) return true;
}
return false;
}
signed main(){
cin>>n>>m;
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++) cin>>a[i][j];
}
if (dfs(1,1)) cout<<"Yes";
else cout<<"No";
return 0;
}
by xhhhh36 @ 2024-08-18 20:11:40
bfs 判边界的地方应该是||,不是&&
by xhhhh36 @ 2024-08-18 20:12:20
@laozhang_123
by lxr_Galaxy @ 2024-08-18 20:15:28
#include<bits/stdc++.h>
using namespace std;
int n,m,k=0,flag=0;
char a[103][103];
int vis[103][103];
int cz(int x,int y){
if(x==n && y==m){
return 1;
}
if(x>n || y>m || x<1 || y<1 || a[x][y]=='#' || vis[x][y]==1) return 0;
vis[x][y]=1;
if(cz(x,y+1))return 1;
if(cz(x+1,y))return 1;
if(cz(x,y-1))return 1;
if(cz(x-1,y))return 1;
return 0;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
if(cz(1,1)) cout<<"Yes";
else cout<<"No";
}
@laozhang_123
by laozhang_123 @ 2024-08-18 20:54:12
@huangshuchang 已关
by laozhang_123 @ 2024-08-18 20:54:53
@xhhhh36 但还是M
by laozhang_123 @ 2024-08-18 20:56:05
@huangshuchang @lxr_Galaxy
DFS已A
by xhhhh36 @ 2024-08-18 21:07:46
@laozhang_123 第25行应该是mp[wx][wy]='#',28行删掉
by laozhang_123 @ 2024-08-18 21:24:01
@xhhhh36 感谢,已A,已关。