上次那种迷宫求解不是最优的解:经过改进后终于找到最优解:请看下面的代码:
#include "stdio.h"
struct {
int i;
int j;
int di;/*下一个可以走的方位*/
}st[50];
int miGong(int x,int y,int xe,int ye){
int i,j,k,di,find; /*find 用于标记是否有下一条路,di是下一个可走的方位号码,k用于循环输出结果*/
int a[10][10]={
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int top=-1;
find=0;/*表示还没找到可走相邻方块*/
top++;
st[top].i=x;st[top].j=y;
st[top].di=-1;a[1][1]=-1;
while(top>-1){
i=st[top].i;j=st[top].j;di=st[top].di; /*取栈顶元素*/
if(i==xe && j==ye){
printf("the migong list:/n");
for(k=0;k<=top;k++){
printf("(%d,%d)/t",st[k].i,st[k].j);
if((k+1)%5==0){
printf("/n");
}
}
printf("/n");
return 1;
}
find=0;
while(di<4 && find==0){
di++;
switch(di){
case 0:i=st[top].i+1;j=st[top].j;break;
case 1:i=st[top].i;j=st[top].j+1;break;
case 2:i=st[top].i-1;j=st[top].j;break;
case 3:i=st[top].i;j=st[top].j-1;break;
}
if(a[i][j]==0){
find=1;
}
}
if(find==1){
st[top].di=di;
top++;
st[top].i=i;
st[top].j=j;
st[top].di=-1;
printf("i=%d,j=%d/n",st[1].i,st[1].j);
a[i][j]=-1;
}else{
/*a[st[top].i][st[top].j]=0;*/
top--;
}
}
return 0;
}
main(){
miGong(1,1,8,8);
getch();
}
#include "stdio.h"
struct {
int i;
int j;
int di;/*下一个可以走的方位*/
}st[50];
int miGong(int x,int y,int xe,int ye){
int i,j,k,di,find; /*find 用于标记是否有下一条路,di是下一个可走的方位号码,k用于循环输出结果*/
int a[10][10]={
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int top=-1;
find=0;/*表示还没找到可走相邻方块*/
top++;
st[top].i=x;st[top].j=y;
st[top].di=-1;a[1][1]=-1;
while(top>-1){
i=st[top].i;j=st[top].j;di=st[top].di; /*取栈顶元素*/
if(i==xe && j==ye){
printf("the migong list:/n");
for(k=0;k<=top;k++){
printf("(%d,%d)/t",st[k].i,st[k].j);
if((k+1)%5==0){
printf("/n");
}
}
printf("/n");
return 1;
}
find=0;
while(di<4 && find==0){
di++;
switch(di){
case 0:i=st[top].i+1;j=st[top].j;break;
case 1:i=st[top].i;j=st[top].j+1;break;
case 2:i=st[top].i-1;j=st[top].j;break;
case 3:i=st[top].i;j=st[top].j-1;break;
}
if(a[i][j]==0){
find=1;
}
}
if(find==1){
st[top].di=di;
top++;
st[top].i=i;
st[top].j=j;
st[top].di=-1;
printf("i=%d,j=%d/n",st[1].i,st[1].j);
a[i][j]=-1;
}else{
/*a[st[top].i][st[top].j]=0;*/
top--;
}
}
return 0;
}
main(){
miGong(1,1,8,8);
getch();
}