1233. 全球变暖 Java题解 (bfs) 【第九届蓝桥杯省赛C++A/B组,JAVA A/B组】

35 篇文章 2 订阅
30 篇文章 1 订阅

 输入样例1:

7
.......
.##....
.##....
....##.
..####.
...###.
.......

输出样例1:

1

输入样例2:

9
.........
.##.##...
.#####...
.##.##...
.........
.##.#....
.#.###...
.#..#....
.........

输出样例2:

1

解题思路:

找被淹没的岛屿的数量,只需要找出该连通块中总有多少陆地,以及有多少陆地与海洋相邻,当二者相等时,该岛屿就会被淹没。

连通块中的陆地总数可以通过对所有进队的岛屿数量做统计;与海洋相邻的岛屿可以通过设置标志变量统计。

Java代码:

import java.io.*;
import java.util.*;

public class Main {
	static int n;
	static char [][]map;
	static boolean [][]vis;
	static int []dx = {-1, 0, 1, 0};
	static int []dy = {0, 1, 0, -1};
	
	static class Point{
		int x, y;
		public Point(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		n = Integer.parseInt(br.readLine());
		map = new char[n][n];
		vis = new boolean[n][n];
		for(int i = 0; i < n; i++) {
			String str = br.readLine();
			for(int j = 0; j < n; j++) {
				map[i][j] = str.charAt(j);
				if(map[i][j] == '#') vis[i][j] = true;
			}
		}
		bfs();
	}
	
	public static void bfs() {
		int ans = 0;
		for(int i = 0; i < n; i++)
			for(int j = 0; j < n; j++) 
				if(vis[i][j]) 
					if(bfs(new Point(i, j)))ans++;
		
		System.out.println(ans);
	}
	
	public static boolean bfs(Point p) {
		Queue<Point> q = new LinkedList<>();
		q.add(p);
		
		int cnt1 = 0;  //连通块中总数
		int cnt2 = 0;  //与海相邻的个数
		while(!q.isEmpty()) {
			Point point = q.poll();
			int x = point.x, y = point.y;
			cnt1++;
			vis[x][y] = false;
			boolean flag = false;
			for(int i = 0; i < 4; i++) {
				int tx = x + dx[i], ty = y + dy[i];
				if(tx < 0 || tx >= n || ty < 0 || ty >= n) continue;
				if(map[tx][ty] == '.') flag = true;  //表明该陆地与海相邻
				if(vis[tx][ty]) {
					q.add(new Point(tx, ty));
					vis[tx][ty] = false;
				}
			}
			if(flag) cnt2++;
		}
		if(cnt1 == cnt2) return true;  //相等时,会被淹没
		return false;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值