백준 4963번: 섬의 개수

HARIBO·2021년 4월 28일
0

풀이

-섬의 배치, 방문 여부를 저장할 2차원 배열 설정
-bfs메소드에서는 시작노드로 주어진 섬과 연결된 섬을 방문처리, 섬의 개수 증가

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

public class Problem4963 {
    static int weight, height = -1;

    static int[] dirX = new int[]{0,0,1,-1,1,1,-1,-1};
    static int[] dirY = new int[]{1,-1,0,0,1,-1,1,-1};
    static int[][] map;
    static boolean[][] visited;
    static int answer = 0;


    public static void bfs(int[] startNode){
        Queue<int[]> queue = new LinkedList<>();

        queue.add(startNode);
        visited[startNode[0]][startNode[1]] = true;


        while(!queue.isEmpty()) {
            int[] currNode = queue.poll();
            for (int d = 0; d < 8; d++) {
                int newX = currNode[1] + dirX[d];
                int newY = currNode[0] + dirY[d];

                if (newX < 0 || newX >= weight || newY < 0 || newY >= height) continue;

                //8방향에 값이 존재 & 미방문
                if (map[newY][newX] == 1 && !visited[newY][newX]) {
                    queue.add(new int[]{newY, newX});
                    visited[newY][newX] = true;
                }
            }
        }
        answer++;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while(true){
            String s = br.readLine();
            //루프 중지
            if(s.equals("0 0")) break;

            StringTokenizer st = new StringTokenizer(s, " ");


            //배열 설정
            weight = Integer.parseInt(st.nextToken());
            height = Integer.parseInt(st.nextToken());
            map = new int[height][weight];
            visited = new boolean[height][weight];


            for(int i = 0; i < height; i++){
                String node = br.readLine();
                StringTokenizer stNode = new StringTokenizer(node, " ");
                for(int j = 0; j < weight; j++){
                    map[i][j] = Integer.parseInt(stNode.nextToken());
                }
            }

            for(int i = 0; i < height; i++){
                for(int j = 0; j < weight; j++){
                    if(!visited[i][j]&&map[i][j]==1){
                        bfs(new int[]{i, j});
                    }
                }
            }
            System.out.println(answer);

            //전역변수 초기화
            answer = 0;
        }
    }

}

0개의 댓글