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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
广搜C代码
#include<stdio.h>
struct note
{
int x;//横坐标
int y;//纵坐标
int f;//父结点位置
int s;//步数
int w;//找到最短路径后,记录当前路径的下一步
};
int main()
{
struct note que[30]; //最多需要5*5个空间
int a[6][6]={0},b[6][6]={0};
int next[4][2]={0,1,1,0,0,-1,-1,0}; //往四个方向走
int head,tail;
int i,j,k,p,q,tx,ty,flag;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
scanf("%d",&a[i][j]);
head=1;
tail=1;
que[tail].x=0;
que[tail].y=0;
que[tail].f=0;
que[tail].s=0;
tail++;
b[0][0]=1;
flag=0; //在到达终点后用作标记
while(head<tail) //无路可走跳出循环,本题可改为1
{
for(k=0;k<3;k++){
tx=que[head].x+next[k][0];
ty=que[head].y+next[k][1];
if(tx<0||tx>4||ty<0||ty>4) continue;
if(a[tx][ty]==0&&b[tx][ty]==0)
{
b[tx][ty]=1;
que[tail].x=tx;
que[tail].y=ty;
que[tail].f=head;
que[tail].s=que[head].s+1;
tail++;
}
if(tx==4&&ty==4){ flag=1; break; } //到达终点
}
if(flag==1)<