/*
2. 上学
记录路径
记录每个点找到最短路时的
上一个点的坐标
queue<int> q;
struct node {
int x, y;
} pre[N][N];
while (!q.empty()){
q.front();
q.pop();
int x, y;
for (){
int nx, ny;
if (越界) continue;
vis[nx][ny = true;
pre[nx][ny] = {now.x, now.y};
q.push();
}
}
找路径代码:
从终点出发
int x = n, y = m;
while (x == 0 && y == 0) {
cout << x << " " << y << "\n";
if (x == 1 && y == 1) break;
node t = pre[x][y];
x = t.x;
y = t.y;
}
题目需要从起点输出到重点,注意需要存下来倒序输出
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, m;
int dx[] = {0, 1, 0, -1};
int dy[] = {-1, 0, 1, 0};
bool vis[N][N];
char s[N][N];
int cnt = 0;
struct node {
int x, y;
int d;
} pre[N][N];
queue<node> q;
bool bfs(int x, int y) {
q.push(node{x, y, 0});
vis[x][y] = true;
// if (x == n && y == m) {
// cnt++;
// return 0;
// }
while (!q.empty()) {
node now = q.front();
q.pop();
//int x, y;
for (int i = 0; i < 4; i++) {
int nx = now.x + dx[i], ny = now.y + dy[i];
if (nx < 0 || nx > n || ny < 0 || ny > m || vis[nx][ny] || s[nx][ny] == '#') continue;
vis[nx][ny] = true;
pre[nx][ny] = {now.x, now.y};
q.push(node{nx, ny, now.d + 1});
}
int xx = n, yy = m;
if (xx == 0 && yy == 0) {
cout << now.d + 1;
return 1;
}
if (!vis[xx][yy]) {
cout << -1;
return 0;
}
while (1) {
cout << xx << " " << yy << "\n";
node t = pre[xx][yy];
xx = t.x;
yy = t.y;
}
}
}
int main ()
{
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> s[i][j];
s[i][j] = s[i][j] + '#';
bfs(i, j);
}
}
return 0;
}
/*
2. 上学
记录路径
记录每个点找到最短路时的
上一个点的坐标
queue<int> q;
struct node {
int x, y;
} pre[N][N];
while (!q.empty()){
q.front();
q.pop();
int x, y;
for (){
int nx, ny;
if (越界) continue;
vis[nx][ny = true;
pre[nx][ny] = {now.x, now.y};
q.push();
}
}
找路径代码:
从终点出发
int x = n, y = m;
while (x == 0 && y == 0) {
cout << x << " " << y << "\n";
if (x == 1 && y == 1) break;
node t = pre[x][y];
x = t.x;
y = t.y;
}
题目需要从起点输出到重点,注意需要存下来倒序输出
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
int n, m;
int dx[] = {0, 1, 0, -1};
int dy[] = {-1, 0, 1, 0};
bool vis[N][N];
char s[N][N];
int cnt = 0;
struct node {
int x, y;
int d;
} pre[N][N];
queue<node> q;
bool bfs(int x, int y) {
q.push(node{x, y, 0});
vis[x][y] = true;
// if (x == n && y == m) {
// cnt++;
// return 0;
// }
while (!q.empty()) {
node now = q.front();
q.pop();
//int x, y;
for (int i = 0; i < 4; i++) {
int nx = now.x + dx[i], ny = now.y + dy[i];
if (nx < 0 || nx > n || ny < 0 || ny > m || vis[nx][ny] || s[nx][ny] == '#') continue;
vis[nx][ny] = true;
pre[nx][ny] = {now.x, now.y};
q.push(node{nx, ny, now.d + 1});
}
int xx = n, yy = m;
if (xx == 0 && yy == 0) {
cout << now.d + 1;
return 1;
}
if (!vis[xx][yy]) {
cout << -1;
return 0;
}
while (1) {
cout << xx << " " << yy << "\n";
node t = pre[xx][yy];
xx = t.x;
yy = t.y;
}
}
}
int main ()
{
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> s[i][j];
s[i][j] = s[i][j] + '#';
bfs(i, j);
}
}
return 0;
}