---
title: "迷宫算法"
author: "JonsenElizee"
date: "2010-10-08T11:06:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2010-10-08T11:06:00Z"
id: 1014910
url: "https://zqs.iteye.com/blog/1014910"
---

Here is a simple implementation for maze issue.

&lt;!--&lt;br&gt;&lt;br&gt;Code highlighting produced by Actipro CodeHighlighter (freeware)&lt;br&gt;http://www.CodeHighlighter.com/&lt;br&gt;&lt;br&gt;--&gt;#include&lt;stdio.h&gt;  
#include&lt;stdlib.h&gt;  
#include&lt;stdext.h&gt;  
#include&lt;stdbool.h&gt;  
#defineROW\_NUM8  
#defineCOL\_NUM8

typedefstruct{  
intx;  
inty;  
structposition\*next;  
}position;

staticintmaze\[ROW\_NUM]\[COL\_NUM]={{0,0,1,0,0,0,0,1},  
{1,1,0,1,1,0,1,0},  
{0,1,0,1,1,0,1,0},  
{0,1,0,1,0,1,0,1},  
{0,1,1,0,1,1,1,1},  
{0,0,0,1,1,0,0,1},  
{1,1,0,1,0,1,1,0},  
{0,0,1,0,1,1,0,0}};

boolisvalid(intx,inty)  
{  
if(x&gt;=0&&x&lt;ROW\_NUM&&y&gt;=0&&y&lt;COL\_NUM&&maze\[x]\[y]==0)returntrue;  
returnfalse;  
}

boolinpath(intx,inty,position\*pos)  
{  
while(pos!=NULL){  
if(pos-&gt;x==x&&pos-&gt;y==y)returntrue;  
pos=(position\*)(pos-&gt;next);  
}  
returnfalse;  
}

staticboolpathfound=false;

voidwalkmaze(intx,inty,position\*pos)  
{  
if(pathfound||!isvalid(x,y)||inpath(x,y,pos))return;  
if(x==ROW\_NUM-1&&y==COL\_NUM-1){  
printf("(%d,%d)",x,y);  
while(pos!=NULL){  
printf("&lt;-(%d,%d)",pos-&gt;x,pos-&gt;y);  
pos=(position\*)pos-&gt;next;  
}  
puts("");pathfound=true;return;  
}  
positionpos6;pos6.x=x,pos6.y=y;pos6.next=pos;walkmaze(x+1,y+1,&pos6);  
positionpos8;pos8.x=x,pos8.y=y;pos8.next=pos;walkmaze(x,y+1,&pos8);  
positionpos5;pos5.x=x,pos5.y=y;pos5.next=pos;walkmaze(x+1,y,&pos5);  
positionpos1;pos1.x=x,pos1.y=y;pos1.next=pos;walkmaze(x-1,y+1,&pos1);  
positionpos2;pos2.x=x,pos2.y=y;pos2.next=pos;walkmaze(x-1,y,&pos2);  
positionpos4;pos4.x=x,pos4.y=y;pos4.next=pos;walkmaze(x+1,y-1,&pos4);  
positionpos7;pos7.x=x,pos7.y=y;pos7.next=pos;walkmaze(x,y-1,&pos7);  
positionpos3;pos3.x=x,pos3.y=y;pos3.next=pos;walkmaze(x-1,y-1,&pos3);  
}

intmain()  
{  
walkmaze(0,0,NULL);  
return0;  
}

![](http://www.cppblog.com/images/cppblog_com/jonsenelizee/2010-10-07-023141_1023x382_scrot.png)