문제설명
현재 방의 구조를 입력받은뒤 로봇청소기의 현재 위치와 현재 방향을 입력받고 로봇청소기가 이 방에서 몇 칸을 청소할 수 있는지 출력하는 문제입니다.
로봇의 이동경로
1. 로봇이 자신의 왼쪽을 확인하고 그쪽으로 회전합니다.
2. 확인한 방향이 청소되어 있지 않은 경우 그 칸으로 이동하고 그 칸을 청소합니다.
3. 확인한 방향이 청소되어 있거나 벽인 경우 다시 왼쪽으로 돌아서 그 방향을 확인합니다.
4. 인접한 위치 모두 청소되어 있거나 벽인 경우 방향을 유지한 채로 한칸 뒤로 후진합니다.
5. 만약 뒷칸이 벽으로 되어있어서 이동이 불가능한 경우 가동을 중지합니다.
작동 순서
1. 맵의 크기를 입력받습니다.
2. 로봇 청소기의 현재 위치와 방향을 입력받습니다.
3. 맵의 구조를 입력받습니다.
4. 로봇의 현재 방향에서 왼쪽을 체크합니다. 그리고 그 방향이 청소가 되어있지 않은 경우 그 방향으로 회전한뒤 그칸으로 이동하여 그 칸을 청소합니다.
5. 현재 바라보고 있는 방향이 청소되어있지 않은 경우 그 방향으로 회전한 뒤 다시 왼쪽 방향을 확인합니다.
6. 사방이 모두 청소되어있으면 현재 바라보고있는 방향에서 뒷칸을 확인합니다.
7. 뒷칸이 벽이 아닌경우 그 칸으로 이동을 하고 뒷칸이 벽인 경우 가동을 종료하고 지금까지 청소한 칸의 수를 출력합니다.
소스코드
import java.io.*;
import java.util.*;
class Robot{
int x;
int y;
int d;
Robot(int x, int y, int d){
this.x = x;
this.y = y;
this.d = d;
}
}
public class 백준_14503번_로봇청소기 {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Queue<Robot> q = new LinkedList<>();
int[][] direction = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
int count = 0;
int N = Integer.parseInt(st.nextToken()), M = Integer.parseInt(st.nextToken());
int[][] map = new int[N][M];
st = new StringTokenizer(br.readLine());
q.add(new Robot(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken())));
for(int i=0;i<N;i++){
st = new StringTokenizer(br.readLine());
for(int j=0;j<M;j++) map[i][j]=Integer.parseInt(st.nextToken());
}
while(!q.isEmpty()){
Robot robot = q.poll();
int x = robot.x;
int y = robot.y;
int d = robot.d;
if(map[x][y]==0) {
map[x][y] = 2;
count++;
}
for(int i=0;i<4;i++){
if(x+direction[d][0]>=0 & x+direction[d][0]<N & y+direction[d][1]>=0 & y+direction[d][1]<M){
if(map[x+direction[d][0]][y+direction[d][1]]==0) {
q.add(new Robot(x+direction[d][0], y+direction[d][1], (d+3)%4));
break;
}
else d = (d+3)%4;
}
else d = (d+3)%4;
if(i==3) {
int backDirect = (d+3)%4;
if (x+direction[backDirect][0] >=0 & x+direction[backDirect][0]<N & y+direction[backDirect][1]>=0 & y+direction[backDirect][1]<M){
if(map[x+direction[backDirect][0]][y+direction[backDirect][1]]!=1) q.add(new Robot(x+direction[backDirect][0], y+direction[backDirect][1], d));
}
}
}
}
System.out.print(count);
}
}