定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
左上角到右下角的最短路径,格式如样例所示。
0 1 0 0 0
0 1 0 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)
在样例输出中,逗号后面有个空格,emmm…鬼知道我找了多久bug
#include
#include
#include
#include
using namespace std;
int maze[5][5];//地图
bool visited[5][5];
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
pair<int,int> p[10][10];//用于存储每个点的前驱结点
stack<pair<int,int> >s;//存放正确路径
void bfs()
{
queue<pair<int,int> >q;
q.push({0,0});
visited[0][0] = true;
while(!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
if(x == 4 && y == 4)
{
while(x > 0 && y >= 0)
{
s.push({x,y});//将结点入栈
pair<int,int> t = p[x][y];
x = t.first;
y = t.second;
}
s.push({0,0});
while(!s.empty())
{
cout << "(" << s.top().first << ", " << s.top().second << ")" <<endl;
s.pop();
}
}
for(int i = 0;i < 4;i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx <= 4 && ny >= 0 && ny <= 4 && maze[nx][ny] == 0 && !visited[nx][ny])
{
visited[nx][ny] = true;
q.push({nx,ny});
p[nx][ny] = {x,y};//点(nx,ny)的前驱结点为(x,y)
}
}
}
}
int main()
{
for(int i = 0;i < 5;i++)
{
for(int j = 0;j < 5;j++)
{
cin >> maze[i][j];
}
}
bfs();
return 0;
}