백준

백준 4963 섬의 개수(Java)

Park DJ 2023. 2. 7. 12:46

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

 

4963번: 섬의 개수

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

www.acmicpc.net


 

해석 및 팁

 


 

이 문제는 dfs를 활용하면 되는 문제입니다. 다만 주의할 점은 확인해야 하는 범위가 상하좌우가 아닌 대각선이 포함된다는 점입니다,

 


 

Java 코드

 


import java.util.Scanner;

public class Main {

  static int w;
  static int h;
  static int[][] arr;
  static boolean[][] visit;
  static int[] lr = {0, 0, -1, 1, -1, -1 , 1, 1};
  static int[] up = {1, -1, 0, 0, 1, -1 , 1, -1};

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    StringBuilder sb = new StringBuilder();
   
    while(true) {
      int count = 0;
      arr = new int[51][51];
      visit = new boolean[51][51];
      w = sc.nextInt();
      h = sc.nextInt();
      if(w == 0 && h == 0) break;
      
      for(int i = 1; i <= h; i++) {
        for(int j = 1; j <= w; j++) arr[i][j] = sc.nextInt();
      }

      for(int i = 1; i <= h; i++) {
        for(int j = 1; j <= w; j++) {
          if(arr[i][j] == 1 && visit[i][j] == false) {
            dfs(i, j);
            count++;
          }
        }
      }
      sb.append(count+"\n");
    }
    
    System.out.println(sb);
  }

  public static void dfs(int a, int b) {
    visit[a][b] = true;
    for(int i = 0; i < 8; i++) {
      int x = a + lr[i];
      int y = b + up[i];
      if(x > 0 && y > 0 && x <= h && y <= w && arr[x][y] == 1 && visit[x][y] == false) dfs(x, y);
    }
  }

}