信息学奥赛一本通(C++版)在线评测系统 (ssoier.cn)
这道题要我们打印从起到到终点的最短路径。
我们需要把路径保存起来,在结构体里放置一个存储数组,数组记录从开始到现在的位置,打印的时候直接遍历输出就可以了。
感觉这道题可以这么做,所以在结构体里放置了一个string(因为string打印方便,存放的时候不需要像数组一样获取长度存储),然后用string记录从0,0到4,4的每一步,然后直接输出。
#include<bits/stdc++.h>
using namespace std;
int n = 5, m = 5;
const int N = 10;
int g[N][N];
bool st[N][N];
struct node
{
int x, y;
string s;
};
queue<node> q;
int dx[4] = { 1,0,0,-1 };
int dy[4] = { 0,-1,1,0 };
void bfs(int n, int m)
{
q.push(node{ 0,0 }); //左上角为起始位置1
st[0][0] = true;
while (!q.empty())
{
node t = q.front();
q.pop();
if (t.x == n - 1 && t.y == m - 1)
{
for (int i = 0; i < t.s.size(); i += 2)
cout << "(" << t.s[i] << ", " << t.s[i + 1] << ")" << endl;
cout << "(4, 4)"; //因为不存放1自身位置,所以需要单独打印
break;
}
for (int i = 0; i < 4; i++)
{
int tx = t.x + dx[i], ty = t.y + dy[i];
if (tx < 0 || tx >= n || ty < 0 || ty >= m || st[tx][ty] || g[tx][ty])continue;
node now = t;
now.x = tx;
now.y = ty;
now.s += t.x + '0';
now.s += t.y + '0';
q.push(now);
st[tx][ty] = true;
}
}
}
int main()
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
bfs(n, m);
return 0;
}