迷宫问题
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
定义一个二维数组:
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
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<stdio.h> int a[5][5],book[6][6] = {0},b[20][2],d[20][2]; int min = 999,c = 1; void dfs(int x,int y,int step)//x,y表示横,纵坐标,steap表示步数 { int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; int i,tx,ty; if(x ==4&&y == 4) { if(step<min)//与最小步数相比,如果小于最小步数,则路径赋值给d数组 { min = step; for(i = 0;i<=step;i++) { d[i][0] = b[i][0]; d[i][1] = b[i][1]; } } return; } for(i = 0;i<4;i++) { tx = x+next[i][0];//枚举四个方向 ty = y+next[i][1]; if(tx<0||tx>4||ty<0||ty>4) continue; if(a[tx][ty] == 0&&book[tx][ty] == 0) { book[tx][ty] = 1; b[c][0] = tx;//把可以走的坐标赋给b数组 b[c][1] = ty; c++;//为记录下一个值做准备 dfs(tx,ty,step+1);//进行下一步 book[tx][ty] = 0; c--;//取消对这个坐标的记录 } } return; } int main() { int i,j; for(i = 0; i<5; i++) for(j = 0; j<5; j++) scanf("%d",&a[i][j]); book[0][0] = 1; b[0][0] = 0;//记录起点坐标 b[0][1] = 0; dfs(0,0,0); for(i = 0;i<=min;i++) printf("(%d, %d)\n",d[i][0],d[i][1]); return 0; }