POJ 3009 Curling 2.0 (dfs)

click me to submit
IN this question , their is a little bit change.first we need to find a far enough location ,than we should go one step further to change the unreachable block reachable , and than take step back to continue.

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#define rep(i, n) for(i;i<n;i++)
#define inf  0x7f7f7f7f7f
using namespace std;
int b[101][101];
int vis[25][25];   //indicate ith number is marked
int n,m;
int ans =11;
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
bool check(int x,int y)
{
    //cout<<"checking:"<<x<<", "<<y<<endl;
    if(x<0||y<0||x>=n||y>=m) return false;
    else return true;
}
void dfs(int x,int y,int step)
{
    //cout<<x<<" "<<y<<" "<<step<<endl;
    if(step>10) return ;
    int leap = 0;
    int xx,yy;
    for(int i=0;i<4;i++)
    {
        leap = 0;
        if(b[x+dx[i]][y+dy[i]] == 1) continue;
        xx = x;
        yy = y;
        while(1)
        {
            xx += dx[i];
            yy += dy[i];
            if(!check(xx,yy))
            {
                leap = 1;
                break;
            }
            if(b[xx][yy] == 1)
            {

                break;
            }
            if(b[xx][yy] == 0)
            {
                continue;
            }
            if(b[xx][yy] == 3)
            {
                ans = min(ans,step);
                return ;
            }
        }

        if(leap) continue;
        b[xx][yy] = 0;
        dfs(xx-dx[i],yy-dy[i],step+1);
        b[xx][yy] = 1;
    }

}
int main()
{

    while(~scanf("%d%d",&m,&n))
    {
        if(!n&&!m) break;
        int sx,sy;
        ans = 11;
        memset(vis,0,sizeof(vis));
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                scanf("%d",&b[i][j]);
                if(b[i][j] == 2)
                {
                    sx = i;
                    sy = j;
                    b[i][j] = 0;
                }
            }
        }
        dfs(sx,sy,0);
        if(ans+1<11)  printf("%d\n",ans+1);
        else printf("-1\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值