返回题解分享
讨论 / 题解分享/ 帖子详情

走迷宫输出路径 - 题解



#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define x first
#define y second

const int N = 20;
char g[N][N];
typedef pair<int, int> PII;
vector<PII> res;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n, m;
bool st[N][N], flag;
int x1, y1, x2, y2;

void dfs(int x, int y)
{
st[x][y] = true;
if(x == x2 && y == y2)
{
flag = true;
printf("(%d,%d)",x1,y1);
for (int i = 1; i < res.size() - 1; i ++ )
printf("->(%d,%d)",res[i].x, res[i].y);
printf("->(%d,%d)\n",x2,y2);
}
for (int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if(a<1 || a>n || b<1 || b>m || st[a][b] || g[a][b]=='0') continue;
st[a][b] = true;
res.push_back({a, b});
dfs(a, b);
res.pop_back();
st[a][b] = false;
}
}

int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> g[i][j];
cin >> x1 >> y1;
cin >> x2 >> y2;

res.push_back({x1, y1});
dfs(x1, y1);
if(!flag) cout << -1;
return 0;


}

0 回复 0 转发 0 喜欢 2 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!