in.add()

[14503] 로봇 청소기 본문

Algorithm/BOJ

[14503] 로봇 청소기

idan 2021. 10. 20. 22:50

문제 링크 : https://www.acmicpc.net/problem/14503

 

14503번: 로봇 청소기

로봇 청소기가 주어졌을 때, 청소하는 영역의 개수를 구하는 프로그램을 작성하시오. 로봇 청소기가 있는 장소는 N×M 크기의 직사각형으로 나타낼 수 있으며, 1×1크기의 정사각형 칸으로 나누어

www.acmicpc.net

 

문제 해결 방법

문제에서 주어진 대로 재귀로 시뮬레이션 구현했다.

 

 

import java.util.Scanner;

public class Main {
    static int N, M, r, c, d, count;
    static int[][] map;
    static int[] dr = {-1, 0, 1, 0};
    static int[] dc = {0, 1, 0, -1};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        map = new int[N][M];
        r = sc.nextInt();
        c = sc.nextInt();
        d = sc.nextInt();
        count = 0;

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                map[i][j] = sc.nextInt();
            }
        }

        clean(r, c, d);
        System.out.println(count + 1);

    }

    private static void clean(int vr, int vc, int vd) {
        map[vr][vc] = -1;

        for(int i = 0; i < 4; i++) {
            vd -= 1;
            if(vd == -1) vd = 3;

            int nextR = vr + dr[vd];
            int nextC = vc + dc[vd];
            if(nextR >= 0 && nextC >= 0 && nextR < N && nextC < M) {
                if(map[nextR][nextC] == 0) {
                    count++;
                    clean(nextR, nextC, vd);
                    return;
                }
            }
        }

        int newD = (vd + 2) % 4;
        int newR = vr + dr[newD];
        int newC = vc + dc[newD];
        if(newR >= 0 && newC >= 0 && newR < N && newC < M && map[newR][newC] != 1) {
            clean(newR, newC, vd);
        }
    }
}

'Algorithm > BOJ' 카테고리의 다른 글

[1647] 도시 분할 계획  (0) 2021.11.02
[14500] 테트로미노  (0) 2021.10.21
[2293] 동전 1  (0) 2021.10.19
[14442] 벽 부수고 이동하기 2  (0) 2021.10.17
[20055] 컨베이어 벨트 위의 로봇  (0) 2021.10.15
Comments