问题描述
定义一个二维数组:
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
代码实现
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
struct node
{
int x,y;
} foot[20];
int maze[10][10];
int flag=0;
int mov[4][2]= {0,1,1,0,-1,0,0,-1};
int vis[20][20]= {0};
void dfs(int x,int y,int step)
{
int i;
if(flag)
return;
if(x==4 && y==4)
{
flag=step;
return;
}
for(i=0; i<4; i++)
{
int next_x=x+mov[i][0];
int next_y=y+mov[i][1];
if(next_x<0||next_y<0||next_x>4||next_y>4)
continue;
if(maze[next_x][next_y]==1)
continue;
if(vis[next_x][next_y])
continue;
vis[next_x][next_y]=1;
foot[step+1].x=next_x;
foot[step+1].y=next_y;
dfs(next_x,next_y,step+1);
if(flag)
return;
vis[next_x][next_y]=0;
}
}
int main()
{
int i,j;
for(i=0; i<5; i++)
{
for(j=0; j<5; j++)
{
scanf("%d",&maze[i][j]);
}
}
foot[0].x=foot[0].y=0;
dfs(0,0,0);
for(i=0; i<=flag; i++)
{
printf("(%d, %d)\n",foot[i].x,foot[i].y);
}
return 0;
}