poj 3009Curling 2.0

/*
2014-5-8
21:34
DFS
poj 3008
*/




#include <cstdio>
#include <string.h>
#define MAXN 30
using namespace std;
//input
int w,h;   //wight  hight
int graph[MAXN][MAXN];
int sx,sy,ex,ey;
int dx[4] = {0,0,-1,1},dy[4] = {-1,1,0,0};
int ans,cnt;

void    dfs(int x,int y,int cnt){
    int nx,ny,i;
    if(cnt > ans)
        return ;

    for(i = 0;i < 4; i++){
        nx = x+dx[i];
        ny = y+dy[i];
        if(nx>=h || nx<0 || ny>=w || ny<0 || graph[nx][ny]==1)//越界或立即有阻挡物剪枝
            continue;
        while(nx <= h && nx>=0 && ny>=0 && ny<=w && graph[nx][ny]!=1){
            if(nx == ex&&ny == ey){
                if(cnt+1 < ans)
                    ans = cnt+1;
                break;
            }
            nx += dx[i];
            ny += dy[i];
        }
        if(nx==ex && ny==ey)//若由于到终点跳出去
            continue;
        if(nx<h && nx>=0 && ny < w && ny>=0)
        {
            graph[nx][ny]=0;//若是碰到阻挡物。阻挡物消失。
            dfs(nx-dx[i],ny-dy[i],cnt+1);//继续搜索
            graph[nx][ny]=1;//还原阻挡物。回溯
        }

    }

}

int main()
{
    while(scanf("%d%d",&w,&h) && w && h){
        ans = 12;

        for(int i = 0;i < h;i++){
            for(int j = 0;j < w; j++){
                scanf("%d",&graph[i][j]);
                if(graph[i][j] == 2){
                    sx = i,sy = j;
                }
                if(graph[i][j] == 3)
                    ex=i,ey=j;
            }
        }

        dfs(sx,sy,0);
        if(ans <= 10)
            printf("%d\n",ans);
        else
            printf("-1\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值