VBGRASS - Bãi cỏ ngon nhất
Tác giả: khuc_tuan
Ngôn ngữ: Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
// BufferedReader kb = new BufferedReader(new
// InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
char[][] a = new char[m][];
for (int i = 0; i < m; ++i)
a[i] = sc.next().toCharArray();
boolean[][] vs = new boolean[m][n];
int dem = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (!vs[i][j] && a[i][j] == '#') {
++dem;
vs[i][j] = true;
Queue<int[]> q = new LinkedList<int[]>();
q.add(new int[] { i, j });
while (!q.isEmpty()) {
int[] ar = q.remove();
int u = ar[0];
int v = ar[1];
for (int dx = -1; dx <= 1; ++dx)
for (int dy = -1; dy <= 1; ++dy)
if ((dx == 0) ^ (dy == 0)) {
int x = dx + u;
int y = dy + v;
if (x < 0 || x >= m || y < 0 || y >= n)
continue;
if (vs[x][y])
continue;
if (a[x][y] == '#') {
vs[x][y] = true;
q.add(new int[] { x, y });
}
}
}
}
System.out.println(dem);
}
}