且未

博客园 首页 新随笔 联系 订阅 管理

题目

#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\n");
        else printf("%d\n",mi);
    }
    return 0;
}

 

posted on 2018-10-18 15:29  阿聊  阅读(72)  评论(0编辑  收藏  举报