我简单粗略的用了两种方法,入门dfs,bfs题 这种题我第一眼就想直接dfs

#include<bits/stdc++.h>
using namespace std;
bool vis[502][502];
bool re[502][502];
int n,m;int ex,ey,sx,sy;
bool flag;
void dfs(int x,int y){
    if(x==ex&&y==ey) {flag=true;return;}
    if(x<=0||y<=0||x>n||y>m||vis[x][y]||re[x][y]==false) return;
      vis[x][y]=true;
      dfs(x+1,y);
      dfs(x-1,y);
      dfs(x,y-1);
      dfs(x,y+1);   
      return ;
}
int main(){
     
    while(cin>>n>>m){
     flag=false;
     getchar();
     for(int i=1;i<=n;++i){
       for(int j=1;j<=m;++j){
           vis[i][j]=false;re[i][j]=true;
           char c=getchar();
           if(c=='S') sx=i,sy=j;
           else if(c=='E') ex=i,ey=j;
           else if(c=='#') re[i][j]=false;
        }
        getchar();
      }
      dfs(sx,sy);
      if(flag) cout<<"Yes\n";
      else cout<<"No\n";
    }
    return 0;
}

接下来是bfs,我就在上面代码的基础上随便加了点东西

#include<bits/stdc++.h>
using namespace std;
bool vis[502][502];
bool re[502][502];
queue<pair<int,int>> q;
int n,m;int ex,ey;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
bool check(pair<int,int> a){
     int x=a.first;
     int y=a.second;
    return x>0&&x<=n&&y>0&&y<=m&&vis[x][y]==false&&re[x][y];
}
bool bfs(){
    while(q.size()){
          auto x=q.front();
          q.pop();
          for(int i=0;i<4;++i){
              pair<int,int> jud;
               jud.first=x.first+dir[i][0];
               jud.second=x.second+dir[i][1];
              if(check(jud)){
                 vis[jud.first][jud.second]=1;
                 q.push(jud);
              }
			  if(jud.first==ex&&jud.second==ey) return true;
        }
    }
    return false;
}
int main(){
    
	while(cin>>n>>m){
	 while(!q.empty()) q.pop();
     getchar();
     for(int i=1;i<=n;++i){
       for(int j=1;j<=m;++j){
           char c=getchar();
           if(c=='S') {q.push({i,j});vis[i][j]=true;}
           else if(c=='E') {ex=i,ey=j;vis[i][j]=false;}
           else if(c=='.') {re[i][j]=true;vis[i][j]=false;}
           else  {re[i][j]=false;vis[i][j]=false;}
        }
        getchar();
      }
      bool flag=bfs();
     if(flag) cout<<"Yes\n";
       else cout<<"No\n";
    }
    return 0;
}

感谢tv,感谢所有tv