第一种,用数组
#include <iostream>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 200;
int n, m;
int g[N][N];
int d[N][N];
PII q[N * N], Prev[N][N];
int bfs()
{
int hh = 0, tt = 0;
q[0] = {0, 0};
memset(d, -1, sizeof(d));
d[0][0] = 0;
//四个方向的向量
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (hh <= tt)
{
PII t = q[hh++];
for (int i = 0; i < 4; i++)
{ int x = t.first + dx[i], y = t.second + dy[i];
//if (x >= 0 && x < n && y >= 0 && y < n && g[x][y] == 0 && d[x][y] == -1) 打错字母了
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y]= d[t.first][t.second] + 1;
Prev[x][y] = t;
q[++tt] = {x, y};
}
}
}
/*
int x = n - 1, y = m - 1;
while (x || y)
{
cout << x << ' ' << y << endl;
PII t = Prev[x][y];
x = t.first, y = t.second;
}
*/
return d[n - 1][m - 1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
cout << bfs() << endl;
/*
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
printf("%3d", d[i][j]);
cout << endl;
}
*/
return 0;
}
第二种,用queue< >
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 110;
typedef pair<int, int> PII;
int n, m;
int g[N][N], d[N][N];
int bfs()
{
queue< pair<int, int> > q;
memset(d, -1, sizeof(d));
d[0][0] = 0;
q.push({0, 0});
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
while (q.size())
{
PII t = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = t.first + dx[i], y = t.second + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y] = d[t.first][t.second] + 1;
q.push({x, y});
}
}
}
return d[n - 1][m -1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
cout << bfs() << endl;
return 0;
}
打印路径(维护路线
)
- bfs进入队列的时候,维护前一步的位置
- 从最后一点倒序到起点,把每一步都放到一个队列或栈里面
- 把队列从front()开始弹空(再逆序回来)
- 要手写队列,否则要使用双端队列
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 110;
typedef pair<int, int> PII;
int n, m;
int g[N][N], d[N][N];
PII Prev[N][N];
PII path[N * N];
int bfs()
{
queue< pair<int, int> > q;
memset(d, -1, sizeof(d));
d[0][0] = 0;
q.push({0, 0});
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
while (q.size())
{
PII t = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = t.first + dx[i], y = t.second + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y] = d[t.first][t.second] + 1;
q.push({x, y});
Prev[x][y] = t;
}
}
}
return d[n - 1][m -1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
cout << bfs() << endl;
int hh = 0, tt = 0;
int x = n - 1, y = m - 1;
while (x || y)
{
path[++tt] = {x, y};
PII t = Prev[x][y];
x = t.first, y = t.second;
}
path[++tt] = {0, 0};
while (hh < tt)
{
PII t = path[tt--];
printf("==>%d %d\n", t.first, t.second);
}
return 0;
}