递归算法求解迷宫问题

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

其实,求解迷宫问题的最好思想是递归,下面通过递归实现求解迷宫内所有的路径。实验代码为:

#include"stdafx.h"

#include"example35_maze.h"

int maze[9][9]={

1,1,1,1,1,1,1,1,1,

1,0,0,0,0,0,0,0,1,

1,0,1,1,0,1,1,0,1,

1,0,1,0,0,1,0,0,1,

1,0,1,0,1,0,1,0,1,

1,0,0,0,0,0,1,0,1,

1,1,0,1,1,0,1,1,1,

1,0,0,0,0,0,0,0,1,

1,1,1,1,1,1,1,1,1

};

void printmaze()

{

int i,j;

for(i=0;i<9;i++)

{

for(j=0;j<9;j++)

{

if(maze[i][j] == 1)

cout<<"*";

else if(maze[i][j]== -1)

cout<<"o";

else

cout<<" ";

}

cout<

}

}

void pass(int x,int y)

{

maze[x][y]=-1;

if(x==7 && y==7)

{

cout<<"road: "<

printmaze();

}

if(maze[x][y+1]==0)

pass(x,y+1);

if(maze[x+1][y]==0)

pass(x+1,y);

if(maze[x-1][y]==0)

pass(x-1,y);

if(maze[x][y-1]==0)

pass(x,y-1);

maze[x][y]=0;

}

int main(void)

{

int Inx=1,Iny=1;

cout<<"the maze information is: "<

printmaze();

pass(Inx,Iny);

return 0 ;

}

实验结果为:

相关文档
最新文档