[백준/자바] 4963. 섬의 개수

Romy·2023년 11월 14일
0

📌 문제


문제

정사각형으로 이루어져 있는 섬과 바다 지도가 주어진다. 섬의 개수를 세는 프로그램을 작성하시오.

!https://www.acmicpc.net/upload/images/island.png

한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사각형이다.

두 정사각형이 같은 섬에 있으려면, 한 정사각형에서 다른 정사각형으로 걸어서 갈 수 있는 경로가 있어야 한다. 지도는 바다로 둘러싸여 있으며, 지도 밖으로 나갈 수 없다.

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다.

둘째 줄부터 h개 줄에는 지도가 주어진다. 1은 땅, 0은 바다이다.

입력의 마지막 줄에는 0이 두 개 주어진다.

출력

각 테스트 케이스에 대해서, 섬의 개수를 출력한다.

예제 입력 1

1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0

예제 출력 1

0
1
1
3
1
9

📌 풀이


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

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

class Main {
    public static int w, h;
    public static int result;
    public static int[][] map;
    public static boolean[][] visit;
    public static int[] dx = {1, 0, -1, 0, 1, 1, -1, -1};
    public static int[] dy = {0, 1, 0, -1, 1, -1, 1, -1};
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        while(true) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            w = Integer.parseInt(st.nextToken());
            h = Integer.parseInt(st.nextToken());

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

            map = new int[h+1][w+1];
            visit = new boolean[h+1][w+1];
            result = 0;
            for(int i=1; i<=h; i++) {
                st = new StringTokenizer(br.readLine());
                for(int j=1; j<=w; j++) {
                    map[i][j] = Integer.parseInt(st.nextToken());
                }
            }
            for(int i=1; i<=h; i++) {
                for(int j=1; j<=w; j++) {
                    if(map[i][j] == 1 && !visit[i][j]) {
                        //System.out.println("시작 -> (" + j + "," + i + ")");
                        result++;
                        dfs(i, j);
                    }
                }
            }
            sb.append(result);
            System.out.println(result);
        }
    }
    public static void bfs(int y, int x) {
        Queue<Node> queue = new LinkedList<>();
        queue.add(new Node(y, x));
        visit[y][x] = true;

        while(!queue.isEmpty()) {
            Node node = queue.poll();
            for(int i=0; i<8; i++) {
                int nextY = node.y + dy[i];
                int nextX = node.x + dx[i];

                if(nextY<1 || nextY>h || nextX<1 || nextX>w) continue;
                if(map[nextY][nextX] == 0 || visit[nextY][nextX]) continue;

                visit[nextY][nextX] = true;
                queue.add(new Node(nextY, nextX));
            }
        }
    }
}

📌 기록


문제 자체는 어려운 문제는 아니었습니다. bfs를 사용하여 queue + dx, dy 조합을 사용해서 다음 위치에 갈 수 있는지 확인하면 되는 문제였는데요. 근데 정답이 자꾸 틀려서 왜지? 하고 찬찬히 문제를 다시 읽어봤더니, 역시나 문제를 대충 읽은 저의 탓이었습니다. 이 문제는 특이하게 “대각선” 까지 이어지는 것으로 체크하는 문제였습니다. 그래서 dy, dx에 대각선까지 이동할 수 있도록 수정하고, 범위도 <4 에서 <8로 수정했습니다. 그랬더니 정답이 잘 나왔습니다.

profile
👩‍💻 IT Engineering

0개의 댓글