poj 3009

因为有对步数的限制,这个题可以直接暴力dfs。


需要注意的是,在选择方向的时候才加一个步数。能撞墙的前提得是,这个球是运动的。


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 20 + 5;
bool G[maxn][maxn];
int r, c;
struct node
{
    int x, y;
    node(int a, int b): x(a), y(b) {}
    node()
    {
        x = y = 0;
    }
} s, g;
int ans;
int dir[][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
bool is_right(int x, int y)
{
    if(x <= r && x>= 1 && y <= c && y >= 1) return true;
    return false;
}
void dfs(int x, int y, int m, int d)
{
    if(m > 10) return;
    //printf("%d %d %d\n", x, y, d);
    if(x == g.x && y == g.y) {ans = min(ans, m); return;}
    if(d == -1)
    {
        for(int i = 0; i < 4; i++)
        {
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(is_right(tx, ty))
            {
                if(!G[tx][ty]) dfs(tx, ty, m + 1, i);
            }
        }
    }
    else
    {
        int tx = x + dir[d][0];
        int ty = y + dir[d][1];
        if(is_right(tx, ty))
        {
            if(G[tx][ty])
            {
                G[tx][ty] = 0;
                dfs(x, y, m, -1);
                G[tx][ty] = 1;
            }
            else dfs(tx, ty, m, d);
        }
    }
}
int main()
{
    while(scanf("%d%d", &c, &r) == 2 && r && c)
    {
        memset(G, 0, sizeof(G));
        for(int i = 1; i <= r; i++)
        {
            for(int j = 1; j <= c; j++)
            {
                int t;
                scanf("%d", &t);
                if(t == 2) s = node(i, j);
                else if(t == 3) g = node(i, j);
                if(t == 1) G[i][j] = 1;
            }
        }
        ans = maxn * maxn;
        dfs(s.x, s.y, 0, -1);
        printf("%d\n", ans == maxn * maxn ? -1 : ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值