打印迷宫最短路径
写完了迷宫,但是想打出起点至终点的最短路径,但是有问题,请各位高手帮我看看:#include <stdio.h>
#include <stdlib.h>
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int visit[100][100];
int ans=0;
int judge(int x,int y,int n,int m,int map[100][100])
{
//printf("\n%d %d %d %d ",x+1,y+1,n,m);
if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]==0&&visit[x][y]==0)
{
//printf("%d",map[x][y]);
visit[x][y]=1;
return 1;
}
return 0;
}
void print(int queue[40000][3],int tail)
{
int i=tail;
while(i!=0)
{
printf("%d %d\n",queue[i][0],queue[i][1]);
i=queue[i][2];
}
}
void dfs(int map[100][100],int n,int m,int startx,int starty,int endx,int endy)
{
int queue[40000][3];
int head=0,tail=1,x,y,xx,yy,i;
memset(queue,0,sizeof(queue));
queue[0][0]=startx;queue[0][1]=starty;
queue[0][2]=0;
while(head<tail)
{
x=queue[head][0];
y=queue[head][1];
ans=queue[head][2];
if(x==endx&&y==endy)
{
print(queue,tail);
printf("%d\n",ans);
return ans;
}
head++;
for(i=0;i<4;i++)
{
xx=x+dx[i];
yy=y+dy[i];
if(judge(xx,yy,n,m,map)==1)
{
queue[tail][0]=xx;
queue[tail][1]=yy;
queue[tail][2]=ans+1;
tail++;
}
}
}
printf("No Answer!\n");
}
int main()
{
int map[100][100],n,m,startx,starty,endx,endy;
int i,j;
scanf("%d %d",&n,&m);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&map[i][j]);
scanf("%d %d",&startx,&starty);
scanf("%d %d",&endx,&endy);
startx--;starty--;
endx--;endy--;
dfs(map,n,m,startx,starty,endx,endy);
system("pause");
return 0;
}
[ 本帖最后由 sunyh1999 于 2011-4-30 09:41 编辑 ]