用堆栈实现走迷宫
程序员文章站
2022-05-20 20:08:50
...
#include <stdio.h>
#include "stack.h"
int map1[9][11]={
{0,0,1,1,0,1,1,0,1,1,1},
{0,1,0,0,0,1,0,0,0,1,0},
{0,1,1,0,1,0,0,0,1,0,0},
{0,0,0,0,1,0,1,0,0,1,0},
{0,1,0,1,0,0,0,1,0,0,0},
{0,1,0,1,0,1,1,1,1,1,0},
{1,0,0,0,0,0,0,1,0,0,0},
{0,0,1,1,1,1,1,1,0,1,1},
{1,0,0,0,0,0,0,1,0,0,0},
};
int map2[][9]={
{0,0,0,0,0,1,0,0,0},
{1,0,0,1,0,0,0,1,0},
};
int sx=0,sy=0;
int tx=8,ty=10;
//保存路径
void show(){
int i,j;
printf("--------------\n");
for(i=0;i<=tx;i++){
printf("|");
for(j=0;j<=ty;j++){
switch(map1[i][j]){
case -1:
case 0:printf(" ");break;
case 1:printf("#");break;
case 2:printf("*");break;
}
}
printf("|\n");
}
printf("--------------\n");
}
int walk(){
Stack s;
stack_init(&s,100);
T pos={sx,sy,N};
stack_push(&s,pos);
map1[0][0]=2;
int nx=0,ny=0;
enum FX dir=RIGHT;
while(1){
pos=stack_top(&s);
if(pos.x==tx && pos.y==ty){
return 0;
}
switch(dir){
case RIGHT:{
if(ny+1<=ty && map1[nx][ny+1]==0){
pos.x=nx;
pos.y=++ny;
pos.dir=dir;
map1[nx][ny]=2;
stack_push(&s,pos);
break;
}else{
dir++;
}
}
case DOWN:{
if(nx+1<=tx && map1[nx+1][ny]==0){
pos.x=++nx;
pos.y=ny;
pos.dir=dir;
map1[nx][ny]=2;
stack_push(&s,pos);
break;
}else{
dir++;
}
}
case UP:{
if(nx-1>=0 && map1[nx-1][ny]==0){
pos.x=--nx;
pos.y=ny;
pos.dir=dir;
map1[nx][ny]=2;
stack_push(&s,pos);
break;
}else{
dir++;
}
}
case LEFT:{
if(ny-1>=0 && map1[nx][ny-1]==0){
pos.x=nx;
pos.y=--ny;
pos.dir=dir;
map1[nx][ny]=2;
stack_push(&s,pos);
break;
}else{
dir++;
}
}
}
if(dir==N){
pos=stack_pop(&s);
if(pos.dir==N){
return -1;
}
dir=pos.dir+1;
map1[nx][ny]=-1;
pos=stack_top(&s);
nx=pos.x;
ny=pos.y;
}else{
dir=RIGHT;
}
}
stack_destroy(&s);
}
int main(){
int res=walk();
if(res==-1){
printf("迷宫无解\n");
}else{
show();
}
return 0;
}
上一篇: 用一个文本文件中存储了名字,写一个程序实现随机获取一个人的名字
下一篇: ES6