编程需要一个正确的逻辑和一条清晰的思路,但能力不强的时候,一开始的逻辑往往是错的,最起初的思路也是不够清晰的,不要急着放弃,急着求助,急着搜,给“受挫”一点时间,给成长一点空间。
#include <iostream>
using namespace std;
int width, height, dw[5] = {0, 1, 0, -1, 0}, dh[5] = {0, 0, 1, 0, -1}, field[27][27], ans[27][27], startH, startW, endH, endW, inf = 0x3f3f3f3f;
void input()
{
for (int h = 1; h <= height; h++)
{
for (int w = 1; w <= width; w++)
{
ans[h][w] = inf;
scanf("%d", &field[h][w]);
if (field[h][w] == 2)
{
startH = h, startW = w;
}
else if (field[h][w] == 3)
{
endH = h, endW = w;
}
}
}
}
bool notBound(int h, int w)
{
return h >= 1 && h <= height && w >= 1 && w <= width;
}
bool isValid(int h, int w)
{
return notBound(h, w) && field[h][w] != 1;
}
void dfs(int h, int w, int step)
{
if (step >= 10)
{
return;
}
for (int i = 1; i <= 4; i++)
{
if (!isValid(h + dh[i], w + dw[i]))
{
continue;
}
int newH = h, newW = w;
while (isValid(newH + dh[i], newW + dw[i]))
{
newH += dh[i], newW += dw[i];
if (step + 1 < ans[newH][newW])
{
ans[newH][newW] = step + 1;
}
}
if (!notBound(newH + dh[i], newW + dw[i]))
{
continue;
}
field[newH + dh[i]][newW + dw[i]] = 0;
dfs(newH, newW, step + 1);
field[newH + dh[i]][newW + dw[i]] = 1;
}
}
int main()
{
while (true)
{
scanf("%d%d", &width, &height);
if (width == 0 || height == 0)
{
break;
}
input();
dfs(startH, startW, 0);
if (ans[endH][endW] > 10)
{
printf("-1\n");
}
else
{
printf("%d\n", ans[endH][endW]);
}
}
return 0;
}