原题链接
Description
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
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
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
题目描述
题意很简单就是0可以走,1不可以走,输出从5*5迷宫,从左上角到右下角的最短路径
思路:一般求最短路径,就需要使用广搜,查找最短步数很简单,但是最短路径,就需要记录路径,这里我们采用一个二维结构数组,在记录每次路径,即保存了当前路径坐标,又能保存上一个路径的坐标,之后使用递归输出就可以,非常巧妙!!
代码如下
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct node
{
int x,y;
}vis[6][6];
//用于存放路径 - 二维数组第一维存放当前路径的x、二维存放y
//.x存放上一个路径的x、.y存放上一个路径的y
int a[6][6],book[6][6]; //book用来标记
int oper[4][2] = {
{0,1},
{1,0},
{0,-1},
{-1,0}
};
void bfs()
{
queue<node> q;
node now;
now.x = now.y = 0;
book[0][0] = 1;
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
for(int i = 0;i < 4;i++)
{
node next;
next.x = now.x + oper[i][0];
next.y = now.y + oper[i][1];
if(next.x>=0 && next.x<5 && next.y>=0 && next.y<5 && !book[next.x][next.y] && a[next.x][next.y]!=1)
{
book[next.x][next.y] = 1;
vis[next.x][next.y] = now; //记录上一个路径信息
q.push(next);
}
if(next.x == 4 && next.y == 4)
return;
}
}
}
//使用递归输出路径
void print(int x, int y)
{
if(x == 0 && y == 0)
printf("(0, 0)\n");
else
{
print(vis[x][y].x, vis[x][y].y);
printf("(%d, %d)\n",x,y);
}
}
int main()
{
int i,j;
for(i = 0;i < 5;i++)
for(j = 0;j < 5;j++)
scanf("%d",&a[i][j]);
bfs();
print(4, 4);
return 0;
}