迷宫 DFS 算法
#include <iostream>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
int map[51][51],vis[51][51];
int N,M;
int sx, sy, ex, ey;
int a[] = { 1, -1, 0, 0 };
int b[] = { 0, 0, 1, -1 };
int min = 99999999;
void dfs(int x, int y, int step){
int tx, ty;
if (x==ex&&y==ey){
if (step < min) min = step;
return;
}
for (int k = 0; k < 4; k++){
tx = x + a[k]; ty = y + b[k];
if (tx<1 || tx>N || ty<1 || ty>M) continue;
if (map[tx][ty] == 1) continue;
if (vis[tx][ty] == 1) continue;
vis[tx][ty] = 1;
dfs(tx,ty,step+1);
vis[tx][ty] == 0;
}
}
int main(){
freopen("input.txt","r",stdin);
int T;
cin >> T;
for (int t = 1; t <= T; t++){
cin >> N >> M;
for (int i = 1; i <= N; i++){
for (int j = 1; j <= M; j++){
cin >> map[i][j];
}
}
cin >> sx >> sy >> ex >> ey;
vis[sx][sy] = 1;
dfs(sx,sy,0);
cout << min;
}
while (1);
return 0;
}