本来是想做一些贪心方面的题目,但却碰到了一道搜索题,拿来练手吧,由于做题搜索方面的题目都是有LD来负责,因此自从去年做完搜索的题目之后,没怎么做过搜索的i题目,当复习了~~~题目对于我这种六级没过的孩子来说,翻译还真是一大问题,一开理解错题意了,导致WA了几次,后来才发现trick所在。唉,还是利用保研这段空闲的时间狂补一下英语吧,理解了题意之后,题目就容易做了~~~
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 30;
const int INF = 0x3f3f3f3f;
const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int map[MAXN][MAXN];
int sx, sy, dx, dy, min_step, W, H;
void dfs(int x, int y, int step)
{
if(step >= 10)
return ;
if(x == dx && y == dy)
{
if(min_step > step)
min_step = step;
return ;
}
for(int i = 0; i < 4; ++i)
{
int tx = x, ty = y;
if(tx + dir[i][0] >= 0 && tx + dir[i][0] < H && ty + dir[i][1] >= 0 && ty + dir[i][1] < W && map[tx+dir[i][0]][ty+dir[i][1]] == 1)
continue;
while(tx >= 0 && tx < H && ty >= 0 && ty < W && (map[tx][ty] == 0 || map[tx][ty] == 2))
tx += dir[i][0], ty += dir[i][1];
if(tx < 0 || tx >= H || ty < 0 || ty >= W)
continue;
else
{
if(map[tx][ty] == 1)
{
map[tx][ty] = 0;
dfs(tx - dir[i][0], ty - dir[i][1], step + 1);
map[tx][ty] = 1;
}
else
dfs(tx, ty, step);
}
}
return ;
}
int main()
{
//freopen("aa.in", "r", stdin);
//freopen("bb.out", "w", stdout);
while(cin >> W >> H)
{
if(W == 0 && H == 0)
break;
for(int i = 0; i < H; ++i)
{
for(int j = 0; j < W; ++j)
{
cin >> map[i][j];
if(map[i][j] == 2)
{
sx = i, sy = j;
}
if(map[i][j] == 3)
{
dx = i, dy = j;
}
}
}
min_step = INF;
dfs(sx, sy, 0);
if(min_step + 1 > 10)
cout << "-1" << endl;
else
cout << min_step + 1 << endl;
}
return 0;
}