其他OJ题目BFS求调
  • 板块灌水区
  • 楼主ZZC_Lingyun
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/11/26 15:44
  • 上次更新2024/11/26 18:59:45
查看原帖
其他OJ题目BFS求调
1277599
ZZC_Lingyun楼主2024/11/26 15:44

33DAI 拿到了一个 行 列的字符型的二维数组,仅由 .#三种字符组成(每个元素都是三种字符之一)。这个二维数组描述了一个迷宫中的情况。. 为空地,# 为墙, 为灯。

灯除了可以照到自己的位置,还可以往上下左右四个方向,照亮其他的空地。从灯的位置,往上下左右照亮的过程中遇到 # 就停止。请你计算一下图中多少位置被照亮了。

比如下面的这个地图中有两盏灯,用 o 描述了样例 1 的地图中灯照亮的空地。

..o..o #oooo ..o..o ..#..o .#ooo .....o 输入格式 第一行一个整数 。

接下来 行,每行 个字符,含义为题目所述的二维迷宫数组。

输出格式 一行一个整数,表示有多少个位置被照亮了。

样例输入 1
6 ......
#....
......
..#...
.#...

......
样例输出 1
15

#include<bits/stdc++.h>
using namespace std;
int n,sum;
char a[35][35];
struct node{
	int x,y;
};
queue<node> q;
void bfs(int qx,int qy,int f){
	node qu;
	q.push({qx,qy});
	while(q.size()){
		qu=q.front();
		if(f==1){
			int nx=qu.x-1,ny=qu.y;
			if(nx<=n&&nx>=1&&ny<=n&&ny>=1&&a[nx][ny]=='.'){
				a[nx][ny]='o';
				q.push({nx,ny});
			}
		}else if(f==2){
			int nx=qu.x,ny=qu.y-1;
			if(nx<=n&&nx>=1&&ny<=n&&ny>=1&&a[nx][ny]=='.'){
				a[nx][ny]='o';
				q.push({nx,ny});
			}
		}else if(f==3){
			int nx=qu.x,ny=qu.y+1;
			if(nx<=n&&nx>=1&&ny<=n&&ny>=1&&a[nx][ny]=='.'){
				a[nx][ny]='o';
				q.push({nx,ny});
			}
		}else{
			int nx=qu.x+1,ny=qu.y;
			if(nx<=n&&nx>=1&&ny<=n&&ny>=1&&a[nx][ny]=='.'){
				a[nx][ny]='o';
				q.push({nx,ny});
			}
		}
	}
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>a[i][j];
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			if(a[i][j]=='*'){
				while(q.size())q.pop();
				bfs(i-1,j,1);
				bfs(i,j-1,2);
				bfs(i,j+1,3);
				bfs(i+1,j,4);
			}
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			if(a[i][j]=='*'||a[i][j]=='o'){
				sum++;
			}
		}
	}
	cout<<sum;
	return 0;
}
2024/11/26 15:44
加载中...