B - Stronger Takahashi ——双端队列模板题

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值