描述
定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示:
int maze[5][5] =
{0, 1, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。入口点为[0,0],既第一格是可以走的路。本题含有多组数据。
输入描述:输入两个整数,分别表示二维数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
输出描述:左上角到右下角的最短路径,格式如样例所示。
示例1
输入:
5 5
0 1 0 0 0
0 1 1 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出:
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)
本题目使用的是BFS,难点在于路径的输出,题目要求的是从左上角
到右下角,那么最后的位置就是右下角位置,在遍历过程中使用prev数组记录了(x,y)坐标位置在遍历时的上一个位置,即Prev[x][y] = t;也就是可以从 t 点到达(x,y)点,循环结束条件是 x 和 y 二者都是0 ,即到达左上角。
数组res记录的结果是从右下角走到左上角的,因此需要reverse,然后输出,注意本题目数多个输入,res不要放置到函数外面,不然多个结果会共同占用一个数组。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int N = 110;
typedef pair<int, int> PII;
PII q[N*N],Prev[N][N];
int g[N][N], d[N][N];
int n, m;
int bfs()
{
vector<vector<int>> res;
queue<PII> q;
q.push({0,0});
memset(d, -1, sizeof d);
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
d[0][0] = 0;
while(!q.empty())
{
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i ++ )
{
int x = dx[i] + t.first, 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;
Prev[x][y] = t;
q.push({x,y});
}
}
}
int x = n - 1, y = m - 1;
while(x || y)//有一个不d等于0
{
res.push_back({x,y});
PII t = Prev[x][y];
x = t.first, y = t.second;
}
res.push_back({x,y});
reverse(res.begin(), res.end());
for(auto x:res)
{
cout << "(" << x[0] << ","<< x[1] << ")"<<endl;
}
return d[n - 1][m - 1];
}
int main()
{
while(cin >> n >> m)
{
for(int i = 0; i < n; i ++ )
for(int j = 0; j < m;j ++)
cin >> g[i][j];
bfs();
}
return 0;
}
用数组实现的队列:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 110;
typedef pair<int, int> PII;
PII q[N*N],Prev[N][N];
int g[N][N], d[N][N];
int n, m;
int bfs()
{
vector<vector<int>> res;
int hh = 0, tt = 0;
q[0] = {0, 0};
memset(d, -1, sizeof d);
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
d[0][0] = 0;
while(hh <= tt)
{
PII t = q[hh ++ ];
for(int i = 0; i < 4; i ++ )
{
int x = dx[i] + t.first, 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;
Prev[x][y] = t;
q[++ tt] = {x, y};
}
}
}
int x = n - 1, y = m - 1;
while(x || y)//有一个不d等于0
{
res.push_back({x,y});
PII t = Prev[x][y];
x = t.first, y = t.second;
}
res.push_back({x,y});
reverse(res.begin(), res.end());
for(auto x:res)
{
cout << "(" << x[0] << ","<< x[1] << ")"<<endl;
}
return d[n - 1][m - 1];
}
int main()
{
while(cin >> n >> m)
{
for(int i = 0; i < n; i ++ )
for(int j = 0; j < m;j ++)
cin >> g[i][j];
bfs();
}
return 0;
}