Description
一个图,只能像马那么跳,求起点到终点最短时间
Algorithm
广搜
Ps
一开始写错一个符合 狂WA
Code
#include <cstring>
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
int n, m;
const int maxn = 100 + 9;
const int inf = 1e8;
char g[maxn][maxn];
struct V
{
int x, y;
V(int x, int y) : x(x), y(y){}
V(){}
};
int a[maxn][maxn];
void print()
{
for (int i = 0; i < n; i++)
{
cout << endl;
for (int j = 0; j < m; j++)
if (a[i][j] == inf) cout << '0'; else cout << a[i][j];
}
cout << endl;
}
bool no(const int &x, const int &y)
{
if ((x < 0) ||
(x >= n)||
(y < 0) ||
(y >= m)||
(g[x][y] == '#')) return false;
return true;
}
void solve()
{
memset(g, 0, sizeof(g));
memset(a, 0, sizeof(a));
for (int i = 0; i < n; i++) scanf("%s", g[i]);
queue<V> v;
V start, ee;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
a[i][j] = inf;
if (g[i][j] == 's')
{
start.x = i;
start.y = j;
}
if (g[i][j] == 'e')
{
ee.x = i;
ee.y = j;
}
}
v.push(start);
a[start.x][start.y] = 0;
while (!v.empty())
{
V now = v.front();
v.pop();
int x = now.x, y = now.y;
int s = a[x][y] + 1;
if (no(x - 2, y + 1) && no(x - 1, y) && a[x - 2][y + 1] > s)
{
a[x - 2][y + 1] = s;
v.push(V(x - 2, y + 1));
}
if (no(x - 2, y - 1) && no(x - 1, y) && a[x - 2][y - 1] > s)
{
a[x - 2][y - 1] = s;
v.push(V(x - 2, y - 1));
}
if (no(x - 1, y + 2) && no(x, y + 1) && a[x - 1][y + 2] > s)
{
a[x - 1][y + 2] = s;
v.push(V(x - 1, y + 2));
}
if (no(x + 1, y + 2) && no(x, y + 1) && a[x + 1][y + 2] > s)
{
a[x + 1][y + 2] = s;
v.push(V(x + 1, y + 2));
}
if (no(x + 2, y + 1) && no(x + 1, y) && a[x + 2][y + 1] > s)
{
a[x + 2][y + 1] = s;
v.push(V(x + 2, y + 1));
}
if (no(x + 2, y - 1) && no(x + 1, y) && a[x + 2][y - 1] > s)
{
a[x + 2][y - 1] = s;
v.push(V(x + 2, y - 1));
}
if (no(x + 1, y - 2) && no(x, y - 1) && a[x + 1][y - 2] > s)
{
a[x + 1][y - 2] = s;
v.push(V(x + 1, y - 2));
}
if (no(x - 1, y - 2) && no(x, y - 1) && a[x - 1][y - 2] > s)
{
a[x - 1][y - 2] = s;
v.push(V(x - 1, y - 2));
}
}
if (a[ee.x][ee.y] == inf) a[ee.x][ee.y] = -1;
printf("%d\n", a[ee.x][ee.y]);
}
int main()
{
// freopen("input.txt", "r", stdin);
while (scanf("%d%d\n", &n, &m) != EOF)
solve();
}