1.做得很痛苦的题,过程清楚,也可以用语句描述出来,但是输出结果这块想不清楚;
2.参考了别人的代码,跟我写的基本上差不多,只是他递归的时候传递了step,我没有传递,但是设的全局变量,为什么就不行啊??
3.这样还一直出错,最后把数组开大了,开到22也不行,直到开到50才AC,为啥啊,范围不就是到20吗?
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int sx, sy, ans;
int w, h;
int dir[4][2]= {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int map[50][50];//我擦,把数组开大了就行了,开成22也不行,为啥啊
int check(int x, int y)
{
if (x >= 0 && x < h && y >= 0 && y < w)
return 1;
else return 0;
}
void dfs(int step, int x, int y)
{
int nx, ny;
if(step >= 10)
// cout << "-1" << endl;
return;
step++;
for(int i = 0; i < 4; i++)
{
nx = x + dir[i][0];
ny = y + dir[i][1];
if(check(nx, ny) && map[nx][ny] != 1)
{
while(check(nx, ny) && map[nx][ny] != 1 && map[nx][ny] != 3)
{
nx += dir[i][0];
ny += dir[i][1];
}
if(map[nx][ny] == 3)
{
if(ans > step)
ans = step;
// cout << ans << endl;
return;
}
else if(map[nx][ny] == 1)
{
map[nx][ny] = 0;
dfs(step, nx - dir[i][0], ny - dir[i][1]);
map[nx][ny] = 1;
}
}
}
return;
}
int main()
{
// cin >> w >> h;
while(scanf("%d%d", &w, &h) != EOF)
{
if(w == 0 && h == 0)
break;
memset(map, 0, sizeof(map));
ans = 100;
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;
// map[i][j] = 0;
}
}
dfs(0, sx, sy);
if(ans < 11)
cout << ans << endl;
else cout << "-1" << endl;
}
return 0;
}