B - Stronger Takahashi
传送门
由题意可以看出,能不用拳就不用拳,所以用双端队列
不需要用拳就加入到队头
需要用拳就加到队尾
在代码中每次出拳并不是要真的将墙打碎,而是将可走的路径全模拟一遍,因为2x2 的方格有四种可能,这四种可能刚好让人周围的八个格子全部覆盖,也就是这一拳给我们接下来走到的路增加了八种可能(上下左右,左上左下右上右下)
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 510;
struct node
{
int a, b, c;
};
int n, m;
bool st[N][N];
char a[N][N];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int bfs()
{
deque<node> q;
q.push_front({0, 0, 0});
while(q.size())
{
node t = q.front();
q.pop_front();
int x = t.a, y = t.b, z = t.c;
if(st[x][y]) continue;
st[x][y] = true;
if(x + 1 == n && y + 1 == m) return z;
for(int i = 0; i < 4; i ++ )
{
int xx = x + dx[i], yy = y + dy[i];
if(xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if(st[xx][yy]) continue;
if(a[xx][yy] == '.')//如果可走,直接如队头
{
q.push_front({xx, yy, z});
}
else//不能走就模拟打一拳后的八条路(上下左右,左上左下右上右下)
{
for(int k = -1; k <= 1; k ++ )
{
for(int j = -1; j <= 1; j ++ )
{
int xxx = xx + k, yyy = yy + j;
if(xxx < 0 || xxx >= n || yyy < 0 || yyy >= m) continue;
if(st[xxx][yyy]) continue;
q.push_back({xxx, yyy, z + 1});
}
}
}
}
}
return -1;
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i ++ ) cin >> a[i];
cout << bfs() << endl;
}