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;
}