第十一届蓝桥杯C++B组国赛试题B:扩散

问题:

image-20210415011931139

答案:20312088

代码:

/*
bfs
*/ 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 10005,P = 3000;	//偏移量 
int map[N][N];
struct Node{
	int x,y;
	int step;
};
const int dir[4][2] = {
	{-1,0},{0,1},{1,0},{0,-1},
};

//相当于起始的时候队列中已经有了4个坐标 
void bfs() {
	queue<Node> que;
	
	//初始坐标都+3000的偏移量 
	map[0+P][0+P] = 1;
	map[2020+P][11+P] = 1;
	map[11+P][14+P] = 1;
	map[2000+P][2000+P] = 1;
	
	que.push({0+P,0+P,0});
	que.push({2020+P,11+P,0});
	que.push({11+P,14+P,0});
	que.push({2000+P,2000+P,0});
	
	while(que.size()) {
		Node cur = que.front();
		que.pop();
		
		if(cur.step == 2020) return;
		
		//往四个方向扩散
		for(int i = 0; i < 4; i++) {
			int tx = cur.x + dir[i][0];
			int ty = cur.y + dir[i][1];
			int ts = cur.step + 1;
			if(tx<0||tx>=N-5||ty<0||ty>=N-5) continue;
			if(map[tx][ty]==1) continue;
			map[tx][ty] = 1;
			que.push({tx,ty,ts});
		}
	}
}

int main() { 
	cout << "开始了" << endl;
	
	bfs();
	
	cout << "输出了" << endl;
	int ans = 0;
	for(int i = 0; i < N-5; i++)
		for(int j = 0; j < N-5; j++)
			if(map[i][j]) ans++;
			
	cout << ans << endl;
	return 0;
}

运行结果:

image-20210415011956151

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值