|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static class Point { |
| 8 | + int r, c; |
| 9 | + public Point(int r, int c) { |
| 10 | + this.r = r; |
| 11 | + this.c = c; |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + static int N, M; |
| 16 | + static int[][] map; |
| 17 | + static boolean[][] visited; |
| 18 | + |
| 19 | + static int[] dr = {-1, 1, 0, 0}; |
| 20 | + static int[] dc = {0, 0, -1, 1}; |
| 21 | + |
| 22 | + public static void main(String[] args) throws IOException { |
| 23 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 24 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 25 | + |
| 26 | + N = Integer.parseInt(st.nextToken()); |
| 27 | + M = Integer.parseInt(st.nextToken()); |
| 28 | + |
| 29 | + map = new int[N][M]; |
| 30 | + visited = new boolean[N][M]; |
| 31 | + |
| 32 | + for (int i = 0; i < N; i++) { |
| 33 | + st = new StringTokenizer(br.readLine()); |
| 34 | + for (int j = 0; j < M; j++) { |
| 35 | + map[i][j] = Integer.parseInt(st.nextToken()); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + int area = 0; |
| 40 | + |
| 41 | + for (int i = 0; i < N; i++) { |
| 42 | + for (int j = 0; j < M; j++) { |
| 43 | + if (map[i][j] == 0 && !visited[i][j]) { |
| 44 | + bfs(i, j); |
| 45 | + area++; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + System.out.println(area); |
| 51 | + } |
| 52 | + |
| 53 | + static void bfs(int sr, int sc) { |
| 54 | + Queue<Point> queue = new LinkedList<>(); |
| 55 | + queue.add(new Point(sr, sc)); |
| 56 | + visited[sr][sc] = true; |
| 57 | + |
| 58 | + while (!queue.isEmpty()) { |
| 59 | + Point current = queue.poll(); |
| 60 | + |
| 61 | + for (int i = 0; i < 4; i++) { |
| 62 | + int nr = (current.r + dr[i] + N) % N; |
| 63 | + int nc = (current.c + dc[i] + M) % M; |
| 64 | + |
| 65 | + if (!visited[nr][nc] && map[nr][nc] == 0) { |
| 66 | + visited[nr][nc] = true; |
| 67 | + queue.add(new Point(nr, nc)); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
0 commit comments