首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

迷宫求解有关问题

2012-11-07 
迷宫求解问题#includestdio.h#includestdlib.h#define n1 10#define n2 10typedef struct node{int x

迷宫求解问题
#include<stdio.h>
#include<stdlib.h>
#define n1 10
#define n2 10
typedef struct node
{
int x;
int y;
int c;
}linkstack;
int maze[n1][n2];
linkstack top[n1*n2];
int i,j,k,m=1,run;
 
void shuru(int g,int h){//输入函数 
 int a,b;
 for(a=0;a<g;a++)
for(b=0;b<h;b++)
scanf("%d",&maze[a][b]);
}

void shuchu(int g,int h){//生成迷宫图样 
int a,b;
  printf("生成的迷宫是:\n");
  for(a=0;a<g;a++)
{ for(b=0;b<h;b++)
  printf(maze[a][b]?"*":" ");
  printf("\n");
}
}

void main()
{ int g,h,v;
  int w;
printf("****************************主菜单***********************\n");  
  printf("***功能1:迷宫求解 *****************\n");
  printf("***功能2:退出系统 *****************\n");
  printf("*********************************************************\n");
  printf("请选择1或2按Enter\n"); 
  scanf("%d",&w);
switch(w)
{ case 1:printf("输入迷宫行数(最大为10):");
scanf("%d",&g);
printf("输入迷宫列数:(最大为10)");
scanf("%d",&h);
printf("大小创建完毕!\n");
printf("请输入迷宫!(0代表路,1代表墙,输入时每行两个数字用空格隔开)\n");  
shuru(g,h);
for(i=0;i<=g*h;i++)
  top[i].c=1;
  shuchu(g,h);
  i=0;
top[i].x=1;
top[i].y=0;
  maze[1][0]=2;
run=1;
v=1;
  do{
  if(top[i].c<5)
{ if(top[i].x==(g-2)&&top[i].y==(h-1))
{ printf("第%d条通路是:\n",m++);
  for(j=0;j<=i;j++)
{printf("(%d,%d)",top[j].x,top[j].y);
if(v!=0) printf("--->");
}
  printf("\n");
  for(j=0;j<g;j++)
{ for(k=0;k<h;k++)
{ if(maze[j][k]==0)
  printf(" ");
  else if(maze[j][k]==2)
  printf("O");
  else printf("*");  
}
  printf("\n");
}
  maze[top[i].x][top[i].y]=0;
  top[i].c=1;
  i--;
  top[i].c+=1;
  continue;

}
  switch(top[i].c)
{ case 0:
{ run=0;
if(v==1)
  printf("此迷宫无通路!");
break;
}
  case 1:
{ if(maze[top[i].x][top[i].y+1]==0)
{ i++;
  top[i].x=top[i-1].x;
  top[i].y=top[i-1].y+1;
  maze[top[i].x][top[i].y]=2;
if(maze[g-2][h-1]==2) v=0;
}
  else top[i].c+=1;
  break;
}
  case 2:
{ if(maze[top[i].x-1][top[i].y]==0)
{ i++;
  top[i].x=top[i-1].x-1;
  top[i].y=top[i-1].y;
  maze[top[i].x][top[i].y]=2;
 
}
  else top[i].c+=1;
  break;
}
  case 3:
{ if(maze[top[i].x][top[i].y-1]==0)
{ i++;
  top[i].x=top[i-1].x;


  top[i].y=top[i-1].y-1;
  maze[top[i].x][top[i].y]=2;

}
  else top[i].c+=1;
  break;
}
  case 4:
{ if(maze[top[i].x+1][top[i].y]==0)
{ i++;
  top[i].x=top[i-1].x+1;
  top[i].y=top[i-1].y;
  maze[top[i].x][top[i].y]=2;
 
}
  else top[i].c+=1;
  break;
}
}
}
  else
{ if(i==0) return v=0;
  maze[top[i].x][top[i].y]=0;
  top[i].c=1;
  i--;
  top[i].c+=1;

}

}while(run==1);
 
break;

case 2: printf("欢迎下次使用!") ;  
break;
  default: break;
}
}
我觉得程序没什么问题,但只能辨别从右边有通路的迷宫,上下通路的直接就说没有通路,比如说
0 0 0 1
0 1 0 1
1 1 0 0
1 1 1 1
这个明显有条路怎么运行时就说没解呢


[解决办法]
没注意数组的边界
改成这个试试
if(maze[top[i].x][top[i].y+1]==0&&top[i].y+1<h)
if(maze[top[i].x-1][top[i].y]==0&&top[i].x-1>=0)
if(maze[top[i].x][top[i].y-1]==0&&top[i].y-1>=0)
if(maze[top[i].x+1][top[i].y]==0&&top[i].x+1<g)

热点排行