回溯算法实例——迷宫

回溯其实是对递归的一种应用,今天写了一个用回溯方法实现的迷宫问题,将代码贴出,并在关键位置进行了注释,请各位指正!

#include "stdafx.h"
#define SIZEOFMAZE 20


char maze[SIZEOFMAZE][SIZEOFMAZE+1]={
"********************",
"*** ***********    #",
"*** ***         * **",
"*** *** ********  **",
"*** *** ********* **",
"***       ******  **",
"*** ************ ***",
"**      ***** ** ***",
"****** ******    ***",
"****** ****** ******",
"******        ******",
"****** ******  *****",
"****** ******* *****",
"****** ******* *****",
"****** ***        **",
"****** *********** *",
"*      *********** *",
"* **************** *",
"                   *",
"********************"
};


/*
typedef struct _tag_pos
{
char x;
char y;
}Pos;
typedef struct _tag_direction
{
char up;
char down;
char left;
char right;
}Direction;
typedef struct _tag_node
{
Pos NPos;
Direction NDirection;
}Node;


Node nodeinfo[SIZEOFMAZE][SIZEOFMAZE]={0};
*/


typedef struct _tag_Pos
{
    int xos;
    int yos;
} Pos;
static Pos pos[]={{0,-1},{-1,0},{0,1},{1,0}};//定义四个方向的移动向量


void display(char (*maze)[SIZEOFMAZE+1])
{
int i=0;
int j=0;
for(i=0;i<SIZEOFMAZE;i++)
{
for(j=0;j<SIZEOFMAZE;j++)
{
printf("%c ",maze[i][j]);
}
printf("\n");
}
}


int findway(char (*maze)[SIZEOFMAZE+1],char x,char y)
{
static int ret=0;//  static

if(maze[x][y] == '#')
{
ret = 1;
display(maze);
}
else
{

for(int i=0;i<4;i++)
{
char nx = x;
char ny = y;
if(nx>=0 && nx<SIZEOFMAZE && ny>=0 && ny<SIZEOFMAZE )
{
nx = nx + pos[i].xos;
ny = ny + pos[i].yos;
if(nx>=0 && nx<SIZEOFMAZE && ny>=0 && (ny<SIZEOFMAZE && maze[nx][ny]==' ' || ny<SIZEOFMAZE && maze[nx][ny]=='#'))
{
if(i==0 || i==2)
{
maze[nx-pos[i].xos][ny-pos[i].yos] = '-';
}
if(i==1 || i==3)
{
maze[nx-pos[i].xos][ny-pos[i].yos] = '|';
}
// display(maze);
// printf("\n");


findway(maze,nx,ny);


if(ret ==1) //如果找到出口了则退出
{
printf("¥\n"); //测试递归结束,结束一次迭代打印一个¥
}
else//如果没找到出口则清楚标记,进行下一次搜索
{
maze[nx-pos[i].xos][ny-pos[i].yos] = ' ';
}
}
}
else
{
printf("Out of the line!\n");
return 0;
}
}


}
return ret;
}


int _tmain(int argc, _TCHAR* argv[])
{
// display(maze);
if(!findway(maze,SIZEOFMAZE-2,0))
{
printf("No way out!\n");
}
return 0;

}


结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值