题目来源:codeup链接
#include <iostream>
#include <vector>
using namespace std;
int n, m;
const int maxn = 30;
const int maxm = 30;
int a[maxn][maxm];
int sx, sy, ex, ey;
bool vis[maxn][maxm] = {false};
bool has = false; //是否存在这样一条路径
int direction[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; //左-上-右-下
struct path
{
int x;
int y;
};
vector<path> Path;
void DFS(int x, int y)
{
if (x == ex && y == ey)
{
has = true;
for (unsigned int i = 0; i < Path.size(); i++)
{
if (i == 0)
{
cout << '(' << Path[i].x << ',' << Path[i].y << ')';
}
else
{
cout << "->(" << Path[i].x << ',' << Path[i].y << ')';
}
}
cout << endl;
return;
}
for (int i = 0; i < 4; i++)
{
int nx = x + direction[i][0];
int ny = y + direction[i][1];
if (nx < 1 || ny < 1 || nx > n || ny > m) //判断是否越界
{
continue;
}
if (vis[nx][ny] == false && a[nx][ny] == 1)//判断是否为障碍物或已经在路径中
{
vis[nx][ny] = true;
path temp;
temp.x = nx;
temp.y = ny;
Path.push_back(temp);
DFS(nx, ny);
vis[nx][ny] = false;
Path.pop_back();
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> a[i][j];
}
}
cin >> sx >> sy;
cin >> ex >> ey;
vis[sx][sy] = true;
path temp;
temp.x = sx;
temp.y = sy;
Path.push_back(temp);
DFS(sx, sy);
if (!has)
{
cout << -1 << endl;
}
return 0;
}