给定一个起始点和一个终止点,在一个迷宫中判断是否能从起始点走到终止点,如果可以输出路径,否则输出
impossible
#include <iostream>
#include <queue>
#include <map>
#include <vector>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII; // 用map 存一下某个坐标是从哪个坐标转移而来
map<PII, PII> mp;
int sx, sy, ex, ey, n, m;
int dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
const int N = 1010;
int g[N][N];
bool st[N][N];
bool bfs() {
queue<PII> q;
if(g[sx][sy] == 1) return false;
q.push(make_pair(sx, sy));
st[sx][sy] = true;
while(q.size()) {
PII t = q.front();
q.pop();
for(int i = 0; i < 8; i ++ ) {
int xx = t.x + dx[i], yy = t.y + dy[i];
if(xx >= 1 && xx <= n && yy <= m && yy >= 1 && !st[xx][yy] && g[xx][yy] == 0) {
PII p = make_pair(xx, yy);
q.push(p);
st[xx][yy] = true;
mp[p] = t;
if(xx == ex && yy == ey) return true;
}
}
}
return false;
}
int main()
{
cin >> sx >> sy >> ex >> ey >> n >> m;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> g[i][j];
if(bfs()) {
vector<PII> v;
PII i = make_pair(ex, ey);
// v.push_back(i);
for(; i != make_pair(sx, sy); i = mp[i]) {
v.push_back(i);
}
v.push_back(make_pair(sx, sy));
int len = v.size() - 1;
for(int i = len; i >= 0; i --) {
cout << v[i].x << ' ' << v[i].y << endl;
}
}
else
cout << "impossible";
// 如果需要用i 就一定要开个新的变量保存一下!!!!!
// i = a[i][j].lx;
// j = a[i][j].ly;
return 0;
}