迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 33756 | Accepted: 19213 |
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)
简单搜索,用一个结构体栈来储存临时路径,一个结构体数组来存储最短路径,实时更新最短路径的结构体数组,最后输出
代码如下:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int maze[5][5];
struct step
{
int tx,ty;
};
step s[10000],t[10000];
int sizee = sizeof(t);
int cou,minn;//cou 为栈顶,minn为走的最小步数
int next[4][2] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} };//上下左右四个方向
void dfs(int x,int y,int dep)//dep代表当前的步数
{
if(dep > minn)//剪枝,当途中步数大于最小步数的时候就已经没有必要再继续了
return;
if((x == 4) && (y == 4))
{
if(dep < minn)//若抵达终点且步数小于minn,更新minn,并将栈拷贝到数组,若无更小最后输出s
{
minn = dep;
memcpy(s,t,sizee);
}
return;
}
for(int i = 0;i < 4; i++)
{
int nx = x + next[i][0];
int ny = y + next[i][1];
if(nx >= 5 || nx < 0 || ny >= 5 || ny < 0 || maze[nx][ny])//越界与标记检查
continue;
t[cou].tx = nx;
t[cou].ty = ny;
cou++;
maze[nx][ny] = 1;
dfs(nx,ny,dep + 1);
maze[nx][ny] = 0;
cou--;
}
}
int main()
{
int x,y;
x = y = 0;
for(int i = 0;i < 5; i++)
for(int j = 0;j < 5; j++)
scanf("%d",&maze[i][j]);
cou = 0,minn = 1 << 30;
t[cou].tx = x,t[cou].ty = y,cou++;//将(0,0)先入栈
maze[0][0] = 1; // 标记起点
dfs(x,y,1);
for(int i = 0;i < minn; i++)
printf("(%d, %d)\n",s[i].tx,s[i].ty);
return 0;
}