#include <bits/stdc++.h>
using namespace std;
struct point {
int x;
int y;
int step;
};
int n, m, sx, sy, ex, ey;
int flag = 1000000;
char temp;
bool tag = false;
bool is_find = false;
int arr[103][103], v[103][103];
void show_v(void) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (v[i][j] != -1) {
cout << " " << v[i][j];
} else {
cout << v[i][j];
}
cout << " ";
}
cout << " ";
for (int j = 1; j <= m; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
bool bfs(int nx, int ny, int step) {
if (is_find) {
//return true;
}
if (arr[nx][ny] != 1) {
return false;
}
if (v[nx][ny] != -1 && step >= v[nx][ny]) {
return false;
}
v[nx][ny] = step;
show_v();
cin >> temp;
if (nx == ex && ny == ey && flag >= step) {
//cout << step << endl;
tag = true;
is_find = true;
if (flag >= step) {
flag = step;
}
//return true;
}
return (
bfs(nx + 1, ny, step + 1)
|| bfs(nx, ny + 1, step + 1)
|| bfs(nx - 1, ny, step + 1)
|| bfs(nx, ny - 1, step + 1)
);
}
void __Input(void) {
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> arr[i][j];
cin >> sx >> sy >> ex >> ey;
for (int i = 0; i <= n + 1; i++)
for (int j = 0; j <= m + 1; j++)
v[i][j] = -1;
}//init
void _Input(void) {
cin >> n;
m = n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
char number = 'a';
cin >> number;
if (number == '0') {
arr[i][j] = 1;
} else {
arr[i][j] = 0;
}
}
cin >> sx >> sy >> ex >> ey;
for (int i = 0; i <= n + 1; i++)
for (int j = 0; j <= m + 1; j++)
v[i][j] = -1;
}//init
int main() {
__Input();
bfs(sx, sy, 0);
if (tag) {
cout << flag;
} else {
cout << "No answer!";
}
return 0;
}
// welldown!
/*
6 6
1 0 1 1 1 1
1 1 1 0 1 0
1 0 1 0 1 1
1 0 1 0 0 1
1 1 0 1 1 1
0 1 0 1 0 1
1 1
6 6
*/
/*
6 8
1 0 1 1 1 1 1 1
1 1 1 0 1 0 0 1
1 0 1 0 1 1 1 1
1 0 1 0 1 1 1 0
1 0 1 1 1 0 1 1
1 1 1 0 1 1 1 1
1 1
6 8
*/
以上代码为初算,运行结果截图
其中01迷宫的dfs搜索c++代码,1表示通路0表示墙。