|
| 1 | +package week03.BOJ_14503_로봇청소기; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.lang.*; |
| 5 | +import java.io.*; |
| 6 | + |
| 7 | +class BOJ14503 { |
| 8 | + static int answer = 0; |
| 9 | + static int N; |
| 10 | + static int M; |
| 11 | + static int[][] room; |
| 12 | + static int[] dx = {-1, 0, 1, 0}; //북동남서 |
| 13 | + static int[] dy = {0, 1, 0, -1}; |
| 14 | + static final int DIRTY = 0; |
| 15 | + static final int WALL = 1; |
| 16 | + static final int CLEANED = 2; |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 20 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 21 | + N = Integer.parseInt(st.nextToken()); |
| 22 | + M = Integer.parseInt(st.nextToken()); |
| 23 | + |
| 24 | + st = new StringTokenizer(br.readLine()); |
| 25 | + int rx = Integer.parseInt(st.nextToken()); |
| 26 | + int ry = Integer.parseInt(st.nextToken()); |
| 27 | + int d = Integer.parseInt(st.nextToken()); |
| 28 | + |
| 29 | + room = new int[N][M]; |
| 30 | + for (int i = 0; i < N; i++) { |
| 31 | + st = new StringTokenizer(br.readLine()); |
| 32 | + for (int j = 0; j < M; j++) { |
| 33 | + room[i][j] = Integer.parseInt(st.nextToken()); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + clean(rx, ry, d); |
| 38 | + System.out.println(answer); |
| 39 | + } |
| 40 | + |
| 41 | + static void clean(int rx, int ry, int d) { |
| 42 | + if (room[rx][ry] == DIRTY) { //현재 칸 청소 |
| 43 | + room[rx][ry] = CLEANED; |
| 44 | + answer++; |
| 45 | + } |
| 46 | + |
| 47 | + if (hasDirty(rx, ry)) { //주변 4칸에 청소되지 않은 칸이 있다면 |
| 48 | + int nd = d == 0 ? 3 : d - 1; //반시계 방향으로 90도 회전 |
| 49 | + int nx = rx + dx[nd]; |
| 50 | + int ny = ry + dy[nd]; |
| 51 | + if (isValid(nx, ny) && room[nx][ny] == DIRTY) { |
| 52 | + clean(nx, ny, nd); |
| 53 | + } else { |
| 54 | + clean(rx, ry, nd); |
| 55 | + } |
| 56 | + |
| 57 | + } else { //없다면 |
| 58 | + //후진했을 때 좌표 |
| 59 | + int nx = rx + (-1) * dx[d]; |
| 60 | + int ny = ry + (-1) * dy[d]; |
| 61 | + if (isValid(nx, ny) && room[nx][ny] != WALL) { |
| 62 | + clean(nx, ny, d); |
| 63 | + } else { |
| 64 | + return; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + static boolean hasDirty(int rx, int ry) { |
| 70 | + for (int i = 0; i < 4; i++) { |
| 71 | + int nx = rx + dx[i]; |
| 72 | + int ny = ry + dy[i]; |
| 73 | + if (isValid(nx, ny) && room[nx][ny] == DIRTY) { |
| 74 | + return true; |
| 75 | + } |
| 76 | + } |
| 77 | + return false; |
| 78 | + } |
| 79 | + |
| 80 | + static boolean isValid(int x, int y) { |
| 81 | + return x >= 0 && x < N && y >= 0 && y < M; |
| 82 | + } |
| 83 | + |
| 84 | +} |
0 commit comments