全球变暖

import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main_9 {

	/**
	 * 
	 * 
	 * 
	 * @param args
	 */
	static int[] dx = { -1, 1, 0, 0 };
	static int[] dy = { 0, 0, -1, 1 };
	// 数据闺蜜
	private static int n;
	// 地图数据
	private static char[][] g;
	// 标记每个格子是否被访问
	private static int[][] mark;
	// 结果:被完全淹没的岛屿的数量
	private static int ans;

	public static void main(String[] args) throws FileNotFoundException {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		sc.nextLine();// 读取换行符
		// 初始化地图数据和标记数组
		g = new char[n][n];
		mark = new int[n][n];
		// 读取地图数据
		for (int i = 0; i < n; i++) {
			g[i] = sc.nextLine().toCharArray();
		}
		// 双重循环检测地图上的各个格子。以未被访问的#为起点,做宽搜
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (g[i][j] == '#' && mark[i][j] == 0) {
					bfs(i, j);
				}
			}
		}
		System.out.println(ans);
	}

	private static void bfs(int x, int y) {
		// TODO Auto-generated method stub
		mark[x][y] = 1;
		int cntOfBlock = 0;// 记录陆地的数量
		int cntOfSwed = 0;// 记录将被淹没的陆地的数量
		Queue<Point> queue = new LinkedList<Point>();
		queue.add(new Point(x, y));
		while (!queue.isEmpty()) {
			Point first = queue.poll();// 弹出头部
			cntOfBlock++;
			boolean swed = false;
			for (int d = 0; d < 4; d++) {
				int nx = first.x + dx[d];
				int ny = first.y + dy[d];
				if (0 <= nx && nx < n && 0 <= ny && ny < n) {
					if (g[nx][ny] == '.')
						swed = true;// 周边有一个。这块陆地就会被淹没,避免重复计数
					if (g[nx][ny] == '#' && mark[nx][ny] == 0) {
						queue.add(new Point(nx, ny));
						mark[nx][ny] = 1;
					}
				}
			}
			if (swed)
				cntOfSwed++;

		}
		if (cntOfBlock == cntOfSwed)
			ans++;
	}

	private static class Point {
		int x, y;

		public Point(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值