πŸ“– [λ°±μ€€μ•Œκ³ λ¦¬μ¦˜ 풀이] Q.4963 μ„¬μ˜ 개수 문제 풀이

πŸ“– 문제

https://www.acmicpc.net/problem/4963

μ •μ‚¬κ°ν˜•μœΌλ‘œ 이루어져 μžˆλŠ” 섬과 λ°”λ‹€ 지도가 주어진닀. μ„¬μ˜ 개수λ₯Ό μ„ΈλŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€.



ν•œ μ •μ‚¬κ°ν˜•κ³Ό κ°€λ‘œ, μ„Έλ‘œ λ˜λŠ” λŒ€κ°μ„ μœΌλ‘œ μ—°κ²°λ˜μ–΄ μžˆλŠ” μ‚¬κ°ν˜•μ€ κ±Έμ–΄κ°ˆ 수 μžˆλŠ” μ‚¬κ°ν˜•μ΄λ‹€. 

두 μ •μ‚¬κ°ν˜•μ΄ 같은 섬에 있으렀면, ν•œ μ •μ‚¬κ°ν˜•μ—μ„œ λ‹€λ₯Έ μ •μ‚¬κ°ν˜•μœΌλ‘œ κ±Έμ–΄μ„œ 갈 수 μžˆλŠ” κ²½λ‘œκ°€ μžˆμ–΄μ•Ό ν•œλ‹€.
μ§€λ„λŠ” λ°”λ‹€λ‘œ λ‘˜λŸ¬μ‹Έμ—¬ 있으며, 지도 λ°–μœΌλ‘œ λ‚˜κ°ˆ 수 μ—†λ‹€.

πŸ” 접근법

μ„¬μ˜ 개수 λ¬Έμ œμž…λ‹ˆλ‹€.

dfs λ‚˜ bfs 탐색을 톡해 λͺ‡κ°œμ˜ κ·Έλž˜ν”„(섬)κ°€ μžˆλŠ”μ§€
μ…€ μˆ˜κ°€ μžˆμŠ΅λ‹ˆλ‹€.

πŸ’» μ½”λ“œ

package problem.bfsdfs;
import java.util.*;

public class Main_4963 {
    static int count;
    static int w;
    static int h;
    static boolean[][] visited;
    static int[][] island;
    static int moveX[] = {0, 0, -1, 1, 1, 1, -1, -1};
    static int moveY[] = {-1, 1, 0, 0, -1, 1, -1, 1};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (true) {
            w = sc.nextInt();
            h = sc.nextInt();

            if (w == 0 && h == 0)
                break;

            island = new int[h][w];

            for (int i = 0; i < h; i++) {
                for (int j = 0; j < w; j++) {
                    island[i][j] = sc.nextInt();
                }
            }

            count = 0;
            visited = new boolean[h][w];

            for (int i = 0; i < h; i++) {
                for (int j = 0; j < w; j++) {
                    if (island[i][j] == 1 && visited[i][j] == false)
                        dfs(i, j, ++count);
                }
            }
            System.out.println(count);
        }

        sc.close();
    }

    public static void dfs(int x, int y, int count) {
        visited[x][y] = true;

        for (int i = 0; i < moveX.length; i++) {
            int nx = x + moveX[i];
            int ny = y + moveY[i];
            if (0 <= nx && nx < h && 0 <= ny && ny < w) {
                if (island[nx][ny] == 1 && visited[nx][ny] == false) {
                    dfs(nx, ny, count);
                }
            }
        }
    }
}
Written on July 14, 2020