迷宫问题的DFS解决(非最短)

本文详细介绍了一种基于栈的迷宫寻路算法,通过定义结构体Point来表示迷宫中的位置,并使用pass函数判断当前位置是否可通过。算法利用栈结构进行路径搜索,从起点开始,尝试向四个方向移动,直到找到终点,最终输出从起点到终点的路径。
#include <iostream>
#include<stack>
#include<queue>
using namespace std;
int a[7][7]=
{{1,1,1,1,1,1,1},
 {1,0,0,0,0,0,1},
 {1,0,1,0,1,0,1},
 {1,0,1,1,0,0,1},
 {1,0,1,1,0,1,1},
 {1,0,0,0,0,0,1},
 {1,1,1,1,1,1,1}
};
struct Point{
int row;
int col;
int p=0;
Point(int x,int y):row(x),col(y),p(0)
{};
bool operator ==(const Point &rhs)
{
    if(this->row==rhs.row&&this->col==rhs.col)
        return true;
    else return false;
}
};
//判断当前的位置是否可以通过
int pass(Point node)
{
    if(a[node.row][node.col]==0&&node.p==0)
        return 1;
    else return 0;
}
//当前位置移动到下一块
 Point nextpos(Point n,int direction)
{
if(direction==1)    n.col++;
if(direction==2)    n.row++;
if(direction==3)    n.col--;
if(direction==4)    n.row--;
      n.p=0;
     return n;
}

void F (Point n,Point m)
{
     if(!(n == m))
        cout<<"OK"<<endl;

}
//寻找路径

 void Findnode(int a[7][7],  const Point &startnode, const Point &endnode)
 {
	 stack<Point>Q;
	 Point curnode = startnode;

	 while (!(curnode == endnode))
	 {
	     //cout<<"diyibu"<<endl;
		 int key = 1;
		 while (pass(curnode))
		 {//cout<<"dierbu"<<endl;
			 if (curnode == endnode)
			 {
				 break;
			 }
			 Q.push(curnode);
			 //a[curnode.row][curnode.col]=1;
			 curnode.p = 1;
			 curnode = nextpos(curnode, 1);

		 }//将可以通过的位置入栈
		 if (curnode == endnode)
		 {
			 break;
		 }
		 curnode = Q.top();
		 for (int i = 2; i <= 4; i++)
		 {    //cout<<"disanbu"<<endl;
			 curnode = nextpos(curnode, i);
			 if (pass(curnode)) break;
			 if (i == 4) key = -1;
		 }//遍历4个方向
		 if (key == -1) Q.pop();//如果四个方向都不行就出栈
	 }
	 if (Q.empty())
	 {
		 cout << "find false" << endl;  return;
	 }//如果没有路径输出find false
	 else
	 {
		 Q.push(endnode);
	 }
	 while (!Q.empty())
	 {
		 Point n = Q.top();
		 cout << "(" << n.row << "," << n.col << ")" << " ";
		 Q.pop();
	 }
	 //反向输出路径
 }

int main()
{   Point startnode(1,1);
    Point endnode (5,5);
    //cout<<(endnode==startnode)<<endl;
    //cout<<nextpos(startnode,1).row<<nextpos(startnode,1).col;
//F(startnode,endnode);

    Findnode(a,startnode,endnode);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值