菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
135
0

迷宫问题 - bfs

原创
05/13 14:22
阅读数 69316

2017-09-28 20:46:06

writer:pprp

题意:

迷宫是一个二维矩阵,其中1为墙,0为路,3为入口,4为出口.要求从入口开始,从出口结束,按照 下,左,上,右 的顺序来搜索路径.

分析:

采用bfs的方法,如果将所有能找到最终终点的路径都压栈,进行存储

代码如下:

#include <iostream>
#include <cstdio>
#include <stack>

using namespace std;
struct node
{
    int a, b;
    friend ostream& operator<<(ostream& os,const node& n)
    {
        os << n.b << " " << n.a << endl;
        return os;
    }
};
stack<node> sk;
int s1,s2,e1,e2;
int w, h;
const int mx = 10000;
int mp[mx][mx];
bool vis[mx][mx];

int dx[] = {1,0,-1,0};
int dy[] = {0,-1,0,1};

bool check(int a, int b)
{
    if(a >= 1 && a <= h &&
            b >= 1 && b <= h && vis[a][b] == 0)
    {
        if(mp[a][b] == 0||mp[a][b] == 4)
            return 1;
    }
    return 0;
}

bool seekPath(int x,int y)
{
    if(x == e1 && y == e2)
        return 1;
    for(int i = 0 ; i < 4; i++)
    {
        int tx = x + dx[i], ty = y + dy[i];
        if(check(tx,ty))
        {
            vis[tx][ty] = 1;
            if(seekPath(tx,ty))
            {
                node *newnode = new node;
                newnode->a = tx;
                newnode->b = ty;
                sk.push(*newnode);
                return 1;
            }
            vis[tx][ty] = 0;
        }
    }
    return 0;
}
int main()
{
    freopen("in.txt","r",stdin);
//    cin >> w >> h;
    scanf("%d%d",&w,&h);
    for(int i = 0 ; i < h ; i++)
        for(int j = 0 ; j < w; j++)
        mp[i][j] = vis[i][j] = 0;

    for(int i = 0 ; i < h ; i++)
    {
        for(int j = 0; j < w; j++)
        {
            cin >> mp[i][j];
            if(mp[i][j] == 3)
                s1 = i,s2 = j;
            if(mp[i][j] == 4)
                e1 = i,e2 = j;
        }
    }
    vis[s1][s2] = 1;
    seekPath(s1,s2);
    cout << s2 << " " << s1 << endl;
    while(!sk.empty())
    {
        cout << sk.top();
        sk.pop();
    }
    return 0;
}

 

发表评论

0/200
135 点赞
0 评论
收藏