POJ 3009 Curling 2.0

本文通过一道搜索题实战,分享了搜索算法的应用与实现细节。作者在解决问题过程中遇到英语障碍,但最终克服并完成题目。代码中使用了深度优先搜索(DFS)解决迷宫最短路径问题。

本来是想做一些贪心方面的题目,但却碰到了一道搜索题,拿来练手吧,由于做题搜索方面的题目都是有LD来负责,因此自从去年做完搜索的题目之后,没怎么做过搜索的i题目,当复习了~~~题目对于我这种六级没过的孩子来说,翻译还真是一大问题,一开理解错题意了,导致WA了几次,后来才发现trick所在。唉,还是利用保研这段空闲的时间狂补一下英语吧,理解了题意之后,题目就容易做了~~~


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 30;
const int INF = 0x3f3f3f3f;
const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int map[MAXN][MAXN];
int sx, sy, dx, dy, min_step, W, H;

void dfs(int x, int y, int step)
{
    if(step >= 10)
        return ;
    if(x == dx && y == dy)
    {
        if(min_step > step)
            min_step = step;
        return ;
    }
    for(int i = 0; i < 4; ++i)
    {
        int tx = x, ty = y;
        if(tx + dir[i][0] >= 0 && tx + dir[i][0] < H && ty + dir[i][1] >= 0 && ty + dir[i][1] < W && map[tx+dir[i][0]][ty+dir[i][1]] == 1)
            continue;
        while(tx >= 0 && tx < H && ty >= 0 && ty < W && (map[tx][ty] == 0 || map[tx][ty] == 2))
                tx += dir[i][0], ty += dir[i][1];
        if(tx < 0 || tx >= H || ty < 0 || ty >= W)
            continue;
        else
        {
            if(map[tx][ty] == 1)
            {
                map[tx][ty] = 0;
                dfs(tx - dir[i][0], ty - dir[i][1], step + 1);
                map[tx][ty] = 1;
            }
            else
                dfs(tx, ty, step);
        }
    }
    return ;
}


int main()
{
    //freopen("aa.in", "r", stdin);
    //freopen("bb.out", "w", stdout);

    while(cin >> W >> H)
    {
        if(W == 0 && H == 0)
            break;
        for(int i = 0; i < H; ++i)
        {
            for(int j = 0; j < W; ++j)
            {
                cin >> map[i][j];
                if(map[i][j] == 2)
                {
                    sx = i, sy = j;
                }
                if(map[i][j] == 3)
                {
                    dx = i, dy = j;
                }
            }
        }
        min_step = INF;
        dfs(sx, sy, 0);
        if(min_step + 1 > 10)
            cout << "-1" << endl;
        else
            cout << min_step + 1 << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值