POJ3009-Curling 2.0

18 篇文章 0 订阅

外星人打冰球的故事。

这是一道深搜的题,与一般的题不同之处在于它并不是走一格,而是走一条直线路径。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int MAXN = 20;

int map[MAXN+2][MAXN+2];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int w, h;
const int INF = 10e6;
int min_step = INF;

void Dfs(int x, int y, int step)
{
    if (map[x][y] == 3) {
        min_step = min(min_step, step);
        return;
    }
    if (step >= min_step || step > 10) {
        return;
    }
    
    int nx, ny;
    int tx, ty;
    for (int i = 0; i < 4; i++) {
        tx = x + dx[i];
        ty = y + dy[i];
        nx = x;
        ny = y;
        
        while (tx >= 0 && tx < h && ty >= 0 && ty < w           //判断下一位置
               && map[tx][ty] != 1) {
            nx += dx[i];
            ny += dy[i];
            if (map[nx][ny] == 3) {
                min_step = min(min_step, step);
                return;
            }
            tx += dx[i];
            ty += dy[i];
            
            if (tx < 0 || tx >= h || ty < 0 || ty >= w) {
                break;
            }
            
            if (map[tx][ty] == 1) {
                map[tx][ty] = 0;
                Dfs(nx, ny, step+1);
                map[tx][ty] = 1;
            }
        }
    }
}

int main()
{
    int x = 0;
    int y = 0;
    
    while (scanf("%d%d", &w, &h) == 2 && w && h) {
        int i, j;
        for (i = 0; i < h; i++) {
            for (j = 0; j < w; j++) {
                scanf("%d", &map[i][j]);
                
                if (map[i][j] == 2) {
                    x = i;
                    y = j;
                }
            }
        }
        
        Dfs(x, y, 1);
        
        if (min_step == INF) {
            printf("-1\n");
        }
        else
            printf("%d\n", min_step);
        
        for (i = 0; i < h; i++) {
            memset(map, 0, sizeof(int) * w);
        }
        min_step = INF;
    }
    
    return 0;
}

使用dx与dy两个数组表示冰壶的方向向量。

nx,ny表示冰壶的位置。

tx,ty用于判断冰壶的下一位置的状态。

有意思的是这道题要求最小步数,因此要搜索所有路径。

搜完某路径后要进行回溯,状态复原。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值