跳到正文

剪贴板

剪贴板 s55xzc9o

原文
剪贴板信息

剪贴板信息

收录
更新

dfs走迷宫

C++
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
int n,m,x,y,ans = inf;
int dir[4][2] = {0,1,0,-1,1,0,-1,0};
int vis[1000][1000];
char maps[1000][1000];
void dfs(int x,int y,int step){
	for(int i = 0;i < 4;i++){
	    int tx = x + dir[i][0];
	    int ty = y + dir[i][1];
	    if(tx <= 0 || tx >= n || ty <= 0 || ty >= m || maps[tx][ty] == 'X' || vis[tx][ty])
	        continue;
	    if(maps[tx][ty] == 'E'){
	        ans = min(ans,step + 1);
	        return;
	    }
	    vis[tx][ty] = 1;
	    dfs(tx,ty,step + 1);
	    vis[tx][ty] = 0;
	}
}
int main(){
	cin >> n >> m;
	for(int i = 1;i <= n;i++){
	    for(int j = 1;j <= m;j++){
	        cin >> maps[i][j];
	        if(maps[i][j] == 'S')
	            x = i,y = j;
	    }
	}
	dfs(x,y,0);
	cout << ans;
	return 0;
}