POJ3009


  
  
#include <stdio.h>
#include <algorithm>
using namespace std;
int map[30][30];
int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
int flag;
int minStep;
int w,h;
void dfs(int x, int y, int step)
{
 
	int nx,ny;
	int tx,ty;
	int px,py;
	if(step > 10)return;
	
	if(map[x][y] == 3)
	{
		minStep = min(minStep, step); 
		return;
	}
	
	for(int i=0; i<4; i++)
	{
		tx = x + dir[i][0];
		ty = y + dir[i][1];
		nx = x;
		ny = y;
	 
		while(tx >= 0 && tx < h && ty >= 0 && ty < w && map[tx][ty] != 1)
		{
			nx += dir[i][0];
			ny += dir[i][1];
 
			if(map[nx][ny] == 3) 
			{
				minStep = min(minStep, step); 
				return;
			}

			tx = nx + dir[i][0];
			ty = ny + dir[i][1];

		 	if(tx < 0 || tx >= h || ty < 0 || ty >= w) 
				  break; 
			if(map[tx][ty] == 1) 
			{
				map[tx][ty] = 0; 
				dfs(nx, ny, step+1);
				map[tx][ty] = 1; 
			}
		}
		
	}
}
int main()
{
	int sx,sy;
	while(scanf("%d %d",&w,&h) != EOF && w != 0 && h != 0)
	{
		minStep = 10000;
		for(int i=0; i<h; i++)
		{
			for(int j=0; j<w; j++)
			{
				scanf("%d",&map[i][j]);
				if(map[i][j] == 2) 
				{
					sx = i;
					sy = j;
				}
			}
		}
		dfs(sx, sy, 1);
		 
		if(minStep == 10000)	printf("-1\n");
			
		else					printf("%d\n",minStep);
			
	}
	return 0;
}
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值