dfs深搜,考虑了左上右下,也写了输出-1的代码
代码如下qwq:
#include <iostream>
using namespace std;
int n, m, sx, sy, ex, ey, nx, ny, te;
int xx[5] = {0, -1, 0, 1, 0};
int yy[5] = {0, 0, 1, 0, -1};
bool ac[16][16], vis[16][16], flag;
struct node{
int x, y;
} a[400];
void print(int step){
for(int i = 1; i < step; i++){
cout << "(" << a[i].x << "," << a[i].y << ")" << "->";
}
cout << "(" << a[step].x << "," << a[step].y << ")" << endl;
}
void dfs(int p, int q, int step){
ac[p][q] = false;
a[step].x = p;
a[step].y = q;
if(p == ex && q == ey){
flag = true;
print(step);
}
for(int i = 1; i <= 4; i++){
nx = p + xx[i];
ny = q + yy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && ac[nx][ny]){
dfs(nx, ny, step + 1);
}
}
ac[p][q] = true;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> te;
if(te == 1){
ac[i][j] = true;
}
}
}
cin >> sx >> sy >> ex >> ey;
dfs(sx, sy, 1);
if(!flag){
cout << "-1" << endl;
}
return 0;
}