개발자-H 입니다.

BOJ - 섬의 개수 (4963) 본문

Algorithm/문제 풀이

BOJ - 섬의 개수 (4963)

개발자-H 2021. 8. 7. 14:00
 

BOJ - 연결 요소의 개수 (11724)

https://www.acmicpc.net/problem/11724 11724번: 연결 요소의 개수 첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와..

developer-h.tistory.com

 

import java.util.Scanner;


public class Main {
    public static final Scanner scanner = new Scanner(System.in);

    public static final int SEA = 0;

    public static void main(String[] args) throws Exception {

        while (true) {
            int W = scanner.nextInt();
            int H = scanner.nextInt();

            if (isTestCaseEnd(W, H)) {
                break;
            }

            if (W == 1 && H == 1) {
                System.out.println(scanner.nextInt());
                continue;
            }

            int[][] map = new int[H + 1][W + 1];
            boolean[][] visited = new boolean[H + 1][W + 1];

            for (int i = 1; i <= H; i++) {
                for (int j = 1; j <= W; j++) {
                    map[i][j] = scanner.nextInt();
                }
            }
            dfs(map, visited);
        }
    }

    private static void dfs(int[][] map, boolean[][] visited) {
        int path = 0;
        for (int i = 1; i < map.length; i++) {
            for (int j = 1; j < map[i].length; j++) {
                if(map[i][j] != SEA && visited[i][j] == false) {
                    path += 1;
                    dfs(i, j, map, visited);
                }
            }
        }
        //경로 횟수 => 연결된 섬 경로의 수
        System.out.println(path);
    }

    private static void dfs(int r, int c, int[][] map, boolean[][] visited) {
        //탐색 종료 조건
        if (r >= map.length || r <= 0) return;
        if (c >= map[r].length || c <= 0) return;
        if (map[r][c] == SEA) return;
        if (visited[r][c] == true) return;

        visited[r][c] = true;

        //가로, 세로, 대각선
        dfs(r, c + 1, map, visited);
        dfs(r, c - 1, map, visited);
        dfs(r + 1, c, map, visited);
        dfs(r - 1, c, map, visited);
        dfs(r + 1, c + 1, map, visited);
        dfs(r - 1, c + 1, map, visited);
        dfs(r + 1, c - 1, map, visited);
        dfs(r - 1, c - 1, map, visited);
    }

    private static boolean isTestCaseEnd(int w, int h) {
        return w == 0 && h == 0;
    }
}

'Algorithm > 문제 풀이' 카테고리의 다른 글

구름 - 길찾기 (다이아몬드)  (0) 2021.08.08
LeetCode - FloodFile  (0) 2021.08.07
BOJ - 단지번호붙이기 (2667)  (0) 2021.08.07
BOJ - 연결 요소의 개수 (11724)  (0) 2021.08.07
프로그래머스 - 가장 먼 노드  (0) 2021.08.04
Comments