Algorithm/baekjoon

로봇청소기(14503)

마닐라 2022. 1. 25. 14:29

📍 문제 설명

 

💡 접근

이코테 책에서 풀었던 시뮬레이션 문제였다.

4번까지 회전해서 갈 수 있으면 청소해주고 갈 수 없으면 뒤로가거나 멈추면 된다.

 

 

👩‍💻 코드

import java.util.*;

public class Main {
    static int n, m, answer, cnt, max, min;
    static int startRobotX, startRobotY, startRobotDireciton;
    static int Hx, Hy, Ex, Ey;
    static int[][] board, clone, dis;
    static boolean[][] visited;
    static int[] ch, pm, combi, graph, go = {1,2,3};
    static boolean flag = false;
    static int[] dx = {-1,0,1,0,}; //북동남서
    static int[] dy = {0,1,0,-1};
    public static void main(String[] args) {
        Main T = new Main();
        Scanner kb = new Scanner(System.in);

        n = kb.nextInt();
        m = kb.nextInt();
        board = new int[n][m];
        //청소 체크
        visited = new boolean[n][m];
        startRobotX = kb.nextInt();
        startRobotY = kb.nextInt();
        startRobotDireciton = kb.nextInt();
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                board[i][j] = kb.nextInt();
            }
        }

        T.solution();
        System.out.println(answer);
    }

    private void solution() {
        Queue<Point> q = new LinkedList<>();
        //로봇지점, 방향, 여태까지 청소한 횟수 넣어두기
        q.add(new Point(startRobotX, startRobotY, startRobotDireciton));
        //현 지점 청소하기
        visited[startRobotX][startRobotY] = true;
        answer++;

        while(!q.isEmpty()) {
            Point cp = q.poll();
            boolean flag = false;
            for(int i = 0; i < 4; i++) {
                //회전시키기
                rotateDirection();
                int nx = cp.x + dx[startRobotDireciton];
                int ny = cp.y + dy[startRobotDireciton];
                //청소할 수 있는 칸이면 전진하고 끝내기
                if(board[nx][ny] == 0 && !visited[nx][ny]) {
                    q.add(new Point(nx, ny, startRobotDireciton));
                    visited[nx][ny] = true;
                    answer++;
                    flag = true;
                    break;
                }
            }
            //4방향 모두 청소 못했으면 c,d 과정 수행
            if(!flag) {
                int nx = cp.x - dx[startRobotDireciton];
                int ny = cp.y - dy[startRobotDireciton];
                //뒤로가!
                if(board[nx][ny] == 0) {
                    q.add(new Point(nx, ny, startRobotDireciton));
                }
                else break;
            }
        }
    }

    //배열은 북동남서 0123
    //회전시에는 서북동남 3012
    private void rotateDirection() {
        startRobotDireciton -= 1;
        if(startRobotDireciton == -1) startRobotDireciton = 3;
    }

    private class Point {
        private int x;
        private int y;
        private int direction;

        public Point(int x, int y, int direction) {
            this.x = x;
            this.y = y;
            this.direction = direction;
        }
    }
}