본문 바로가기
알고리즘 풀이/소프티어

[level 2] 장애물 인식 프로그램 (JAVA)

by cornsilk-tea 2023. 5. 10.

문제 요약

자율주행팀 SW 엔지니어인 당신에게 장애물과 도로를 인식할 수 있는 프로그램을 만들라는 업무가 주어졌다.

 

[그림 1] 지도 예시

 

우선 [그림 1]과 같이 정사각형 모양의 지도가 있다. 1은 장애물이 있는 곳을, 0은 도로가 있는 곳을 나타낸다.

 

당신은 이 지도를 가지고 연결된 장애물들의 모임인 블록을 정의하고, 불록에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 장애물이 좌우, 혹은 아래위로 붙어 있는 경우를 말한다. 대각선 상에 장애물이 있는 경우는 연결된 것이 아니다.

 

 

[그림 2] 블록 별 번호 부여

 

[그림 2]는 [그림 1]을 블록 별로 번호를 붙인 것이다. 

 

지도를 입력하여 장애물 블록수를 출력하고, 각 블록에 속하는 장애물의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.


문제 분석

bfs를 이용해서 블록을 찾고 장애물 개수 계산하기


코드

import java.util.*;
import java.io.*;


public class Main
{
    static List<Integer> list;
    static int N;
    static class Node{
        int r;
        int c;
        public Node(int r, int c){
            this.r = r;
            this.c = c;
        }
    }
    public static void main(String args[]) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        int[][] table = new int[N][N];
        for(int r = 0; r < N; r++){
            table[r] = br.readLine().chars().map(c -> c-'0').toArray();
        }
        list = new ArrayList<>();
        boolean[][] v = new boolean[N][N];
        for(int r = 0; r < N; r++){
            for(int c = 0; c < N; c++){
                if(table[r][c] == 1 && v[r][c] == false){
                    bfs(r, c, table, v);
                }
            }
        }
        Collections.sort(list);
        System.out.println(list.size());
        for(int i : list){
            System.out.println(i);
        }
    }
    static int[] dr = {-1,0,1,0};
    static int[] dc = {0,1,0,-1};
    public static void bfs(int r, int c, int[][] table, boolean[][] v){
    int cnt = 1;  // start the count from 1
    Queue<Node> q = new LinkedList<>();
    q.add(new Node(r, c));
    v[r][c] = true;
    while(!q.isEmpty()){
        Node node = q.poll();
        for(int d = 0; d < 4; d++){
            int nR = node.r + dr[d];
            int nC = node.c + dc[d];
            if(isOutRange(nR,nC) || v[nR][nC] || table[nR][nC] == 0){
                continue;
            }
            q.add(new Node(nR,nC));
            v[nR][nC] = true;
            cnt++;  // increase the count when a new node is visited
        }
    }
    list.add(cnt);
}

    public static boolean isOutRange(int r, int c){
        if(r < 0 || c < 0 || r >= N || c >= N){
            return true;
        }
        return false;
    }
}

정리

새로 배운 내용

없음

개선할 점

변수 함수 이름정하기가 너무 힘들다.

더 찾아볼만한 사항

DFS로도 한번 풀어보자.