链接:https://codeforces.com/problemset/problem/173/B
题目:
思路:
初识01BFS
什么是 01 BFS 呢?通常的 BFS 为一步权值为 1,而某些题需要的不是走到步数,而是某种操作数,如花费一个操作可以走 k 步,而不花费只能走 1 步,通常我们使用双端队列可插队的性质来进行代码的编写,具体的对于不花费,那么就插入到前面,而对于花费则插入到最后
本题中操作为 “四射”,所以按照上面描述很快能写出来代码
代码:
#include <iostream>
#include <algorithm>
#include<cstring>
#include<cctype>
#include<string>
#include <set>
#include <vector>
#include <cmath>
#include <queue>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <stack>
#include <memory>
#include <complex>
using namespace std;
#define int long long
#define yes cout << "Yes\n"
#define no cout << "No\n"
pair<int, int> dir[4] = { {-1,0},{0,1},{1,0},{0,-1} };
int use[1005][1005];
int dis[1005][1005][4];
deque<int> q;
void af(int x,int y,int d,int ans)
{
if (ans < dis[y][x][d])
{
dis[y][x][d] = ans;
q.push_front(d);
q.push_front(y);
q.push_front(x);
}
}
void ab(int x, int y, int d, int ans)
{
if (ans < dis[y][x][d])
{
dis[y][x][d] = ans;
q.push_back(x);
q.push_back(y);
q.push_back(d);
}
}
void solve()
{
int n, m;
cin >> n >> m;
vector<string> mp(n);
for (int i = 0; i < n; i++)
{
cin >> mp[i];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
for (int k = 0; k < 4; k++)
{
dis[i][j][k] = 1e18;
}
}
}
af(m - 1, n - 1, 0, 0);
while (!q.empty())
{
int x = q[0];
int y = q[1];
int d = q[2];
q.pop_front();
q.pop_front();
q.pop_front();
int ans = dis[y][x][d];
int nx = x + dir[d].first;
int ny = y + dir[d].second;
if (nx >= 0 && nx < m && ny >=0 && ny < n)
{
af(nx, ny, d, ans);
}
if (mp[y][x] == '#')
{
for (int i = 0; i < 4; i++)
{
if (i != d)
ab(x, y, i, ans + 1);
}
}
}
if (dis[0][0][0] != 1e18)
cout << dis[0][0][0] << endl;
else
cout << "-1\n";
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
while (t--)
{
solve();
}
return 0;
}