关于八方向的迷宫问题

问题描述:

给定一个迷宫,入口为左上角,出口为右下角,问是否有路径从入口到出口,若有则输出一条这样的路径。注意移动可以从上、下、左、右、上左、上右、下左、下右八个方向进行。迷宫输入0表示可走,输入1表示墙。

算法分析:

此处的思想是,采用堆栈的巧用(或者说就是DFS深度优先搜索的方法)。

# include<stdio.h>
# include<stdlib.h>
# define Max_size 1000
int maze[13][17]={
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,0,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1,
1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1,
1,0,1,1,0,0,0,0,1,1,1,1,0,0,1,1,1,
1,1,1,0,1,1,1,1,0,1,1,1,0,0,1,1,1,
1,1,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1,
1,0,0,1,1,0,1,1,1,0,1,0,0,1,0,1,1,
1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,
1,0,0,1,1,0,1,1,0,1,1,1,1,1,0,1,1,
1,1,1,0,0,0,1,1,0,1,1,0,0,0,0,0,1,
1,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0,1,
1,0,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
};//0表示不通,1表示通
int mark[13][17];//0表示没有检查过,1表示已经检查过;记录已经检测过的,如果不通的话,回溯时就不需要再次访问它了

typedef struct{
short int row;
short int col;
short int dir;
}element;
element stack[Max_size];
void initial(int r,int c,int d,element *ele)
{
ele->row=r;
ele->col=c;
ele->dir=d;
}
void pushstack(int *top,element term)
{
if(*top>Max_size-1)
{
printf(“堆栈太小了!!!”);
   return;
    }
stack[++(*top)]=term;
}
element popstack(int *top)
{
if(*top==-1)
{
printf(“不可以推栈操作,已经空了!!!”);
exit(0);
}
return stack[(*top)–];
}
typedef struct{
short int vert;
short int horiz;
}direc;
direc move[7];
void allinitial()
{
int i=0,j=0;
move[0].vert=-1;
move[0].horiz=0;
move[1].vert=-1;
move[1].horiz=1;
move[2].vert=0;
move[2].horiz=1;
move[3].vert=1;
move[3].horiz=1;
move[4].vert=1;
move[4].horiz=0;
move[5].vert=1;
move[5].horiz=-1;
move[6].vert=0;
move[6].horiz=-1;
move[7].vert=-1;
move[7].horiz=-1;
for(i=0;i<13;i++)
{
for(j=0;j<17;j++)
{
mark[i][j]=0;
}
}

}
void path(int firstdirec)
{

int found=0,top=0;
element start;
allinitial();
initial(1,1,firstdirec,&start);
pushstack(&top,start);
mark[1][1]=1;
while(top>-1&&!found)
{
    element now=popstack(&top);//取当前当前位置,继续当前位置向下扫描。
int row=now.row;
int col=now.col;
int dir=now.dir;
int i=0;
int next_row,next_col;
mark[1][1]=1;
while(dir<8&&!found)//如果找到合适方向,记录该方向,压进栈,深度向下继续搜索直到不合适,返回。
{
next_row=move[dir].vert+row;
next_col=move[dir].horiz+col;
if(next_row==11&&next_col==15)
found=1;
else
if(maze[next_row][next_col]==0&&mark[next_row][next_col]==0)
{
             mark[next_row][next_col]=1;
now.row=row;
now.col=col;
++dir;
now.dir=dir;
pushstack(&top,now);
row=next_row;
col=next_col;
dir=0;
}
else
dir++;
}
}
if(found)
{
int i=0;
printf(“the path is:\n”);
for(i=0;i<=top;i++)
{
printf(“(%d,%d)-“,stack[i].row-1,stack[i].col-1);
}
printf(“(10,14)”);
}
}
int main()
{
path(1);//这个是依据现有迷宫得出的
system(“Pause”);
return 0;
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/u012671925/article/details/44566877
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞