poj 3009 Curling 2.0

题目

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int Max = 0x3f3f3f3f;

int ei,ej;
int steps,mi;
int dir[4][2]= {{-1,0},{1,0},{0,-1},{0,1}};
int w,h;
int mp[25][25];
void dfs(int si,int sj)
{
    int x,y;
    if(steps>=10) return;
    for(int i=0; i<4; i++)
    {
        x = si,y=sj;
        while(1)
        {
            x += dir[i][0];
            y += dir[i][1];
            if(x<=0||x>h||y<=0||y>w) break;
            if(x==ei&&y==ej)
            {
                steps++;
                if(mi>steps) mi = steps;
                steps--;
                return ;
            }
            else if(mp[x][y]==1)
            {
                if(x-dir[i][0]!=si || y-dir[i][1]!=sj)
                {
                    mp[x][y]=0;
                    steps++;
                    dfs(x-dir[i][0],y-dir[i][1]);
                    mp[x][y]=1;
                    steps--;
                }
                break;
            }
        }
    }
}
int main()
{
    int si,sj;
    while(~scanf("%d%d",&w,&h))
    {
        if(w==0||h==0) break;
        for(int i=1; i<=h; i++)
            for(int j=1; j<=w; j++){
                scanf("%d",&mp[i][j]);
                if(mp[i][j]==3){
                    ei = i;
                    ej = j;
                }
                else if(mp[i][j]==2){
                    si = i,sj = j;
                }
            }
        steps = 0;
        mi = Max;
        dfs(si,sj);
        if(mi==Max) printf("-1
");
        else printf("%d
",mi);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/qie-wei/p/10160136.html