迷宫问题

STL讲义上搜索的一道例子,代码是书上的,有点问题改动了一点,二维数组表示的迷宫,0代表没路,1代表有路,采用深度搜索(应该是吧刚学不清楚。。。。

#include<iostream>
#include<vector>
using namespace std;

int maze[4][6] = { {1, 1, 0, 0, 0, 0},
                   {0, 1, 1, 1, 0, 0},
                   {1, 1, 0, 1, 0, 0},
                   {0, 1, 1, 1, 0, 0}};
vector<pair<int, int> > path;

int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//下 右 上 左

void printvector(vector<pair<int, int> > path)
{
    vector<pair<int , int > >::iterator pit;
    for(pit=path.begin();pit != path.end();pit++)
    {
        cout<<pit->first<<","<<pit->second<<" -> ";
    }
    cout<<"3,3"<<endl;
}

void search(vector<pair<int, int> > tpath, int x, int y)
{
    if(x < 0 || y < 0 || x > 5 || y > 3)//越界返回
        return;

    if(x == 3 && y == 3)
    {
        path = tpath; //如果找到了出口,则记录下路径
        printvector(path);
        return;
    }

    for(int ix = 0; ix < 4; ix++)//四个方向搜索
    {
        if(maze[x+dir[ix][0]][ y+dir[ix][1]] == 1)
        {
            tpath.push_back(make_pair(x, y));
            maze[x][y] = 2;
            search(tpath, x+dir[ix][0], y+dir[ix][1]);
            tpath.pop_back();//删除最后一个元素
        }
    }
}
int main()
{
    vector<pair<int, int> > tpath;
    search(tpath, 0, 0);//从开始点找起
    cout<<endl;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值