0
点赞
收藏
分享

微信扫一扫

用栈求解迷宫问题的所有路径及最短路径


#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std ;
const int MAX = 105 ;
int mg[MAX][MAX] ={
{1,1,1,1,1,1},{1,0,0,0,1,1},{1,0,1,0,0,0,1},{1,0,0,0,1,1},{1,1,0,0,0,1},{1,1,1,1,1,1}

};//迷宫地图

struct Point{
int x ;// 路径横坐标
int y ;// 路径纵坐标 ;
int di ;// 方向
};
typedef struct{
int top ;
Point data[MAX] ;
}Stack;
class STACK{

public:
void InitStack(Stack *&s);
bool StackEmpty(Stack *&s);
bool Push(Stack *&s ,Point &e);
bool Pop(Stack *&s ,Point &e);
bool GetTop(Stack *&s ,Point &e);
};
void STACK::InitStack(Stack *&s)
{
s = (Stack *)malloc(sizeof(Stack)) ;
s->top = -1 ;
return ;
}
bool STACK::StackEmpty(Stack *&s)
{
return (s->top ==-1) ;
}
bool STACK::Push(Stack *&s ,Point &e)
{
if(s->top == MAX -1)
{
return false ;
}
s->top++ ;
s->data[s->top] = e ;
return true ;
}
bool STACK::Pop(Stack *&s ,Point &e)
{
if(s->top ==-1)
{
return false ;
}
e = s->data[s->top] ;
s->top-- ;
return true ;

}
bool STACK::GetTop(Stack *&s ,Point &e)
{
if(s->top ==-1)
{
return false ;
}
e = s->data[s->top ] ;
return true ;
}
int count = 1 ; // 记录路径数目
int minlen = 0x3f3f ;
Point path[MAX] ;
void dfs(Point start ,Point end)
{
bool find ;
Point head ;
STACK a ;
Stack *s ;
a.InitStack(s);
start.di = -1 ;// 开始点,且还没有尝试 ;
a.Push(s,start);
mg[start.x][start.y] = -1 ;
while(!a.StackEmpty(s))
{
head;// 栈顶元素
a.GetTop(s,head) ;
if(head.x == end.x && head.y == end.y)
{
count++ ;
printf("Map %d :\n",count-1);
for(int k = 0 ;k<=s->top ;k++)
{
printf("(%d ,%d) ",s->data[k].x,s->data[k].y);

if((k+1)%5==0)
cout<<endl;
}

printf("\n\n");
if(s->top+1 <minlen)
{
for(int k = 0 ;k<=s->top ;k++)
{
path[k] = s->data[k] ;
}
// 更新最短路径
minlen = s->top+1 ;
}
// 退栈,重新走
mg[s->data[s->top].x][s->data[s->top].y] = 0 ;
s->top--;
head.x = s->data[s->top].x ;
head.y = s->data[s->top].y ;
head.di = s->data[s->top].di ;

}
find = false ;

while(head.di<4 && !find)
{
head.di++ ;
switch(head.di){

case 0:head.x=s->data[s->top].x -1 ;head.y =s->data[s->top].y;break; //上面

case 1:head.x=s->data[s->top].x ;head.y =s->data[s->top].y+1;break; //右边

case 2:head.x=s->data[s->top].x +1 ;head.y =s->data[s->top].y;break; //下面

case 3:head.x=s->data[s->top].x ;head.y =s->data[s->top].y-1;break; //左边
}

if(mg[head.x][head.y]==0)
{
find = true ;
}

}

if(find)
{
//如果有路
s->data[s->top].di = head.di ; // 修改原来栈顶的方向值
s->top++;
s->data[s->top].x = head.x ;// 入栈
s->data[s->top].y = head.y ;
s->data[s->top].di = -1 ;// 此点还没有进行过尝试
mg[head.x][head.y] = -1 ;//访问过了
}
else
{
//回溯
mg[s->data[s->top].x][s->data[s->top].y] = 0 ;
s->top --;
}

}

printf("最短路径长度为 :%d\t",minlen);
printf("最短路径 : \n");
for(int k = 0 ;k <minlen ;k++)
{
printf("\t\t\t(%d,%d)\n",path[k].x,path[k].y) ;
}
cout<<endl;

}
int main()
{
Point start ,end ;
start.x = 1 ;
start.y = 1 ;
end.x = 4 ;
end.y = 4 ;
dfs(start,end);

return 0 ;
}

 

举报

相关推荐

0 条评论