https://www.acmicpc.net/problem/14503
14503번: 로봇 청소기
로봇 청소기가 주어졌을 때, 청소하는 영역의 개수를 구하는 프로그램을 작성하시오. 로봇 청소기가 있는 장소는 N×M 크기의 직사각형으로 나타낼 수 있으며, 1×1크기의 정사각형 칸으로 나누어
www.acmicpc.net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
// 로봇 청소기 | |
@SuppressWarnings("unchecked") | |
class Main { | |
static int n, m, r, c, d, cleaning = 0; | |
static int[][] map , dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 북동남서 | |
public static void main(String[] args) throws IOException { | |
input(); | |
process(); | |
System.out.println(cleaning); | |
} | |
static void input() throws IOException { | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
StringTokenizer st = new StringTokenizer(br.readLine()); | |
n = Integer.parseInt(st.nextToken()); | |
m = Integer.parseInt(st.nextToken()); | |
map = new int[n][m]; | |
st = new StringTokenizer(br.readLine()); | |
r = Integer.parseInt(st.nextToken()); | |
c = Integer.parseInt(st.nextToken()); | |
d = 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()); | |
} | |
} | |
} | |
static void process() { | |
boolean canCleaning = true; | |
// 회전 횟수 | |
int count = 0; | |
int x = r; | |
int y = c; | |
while (true) { | |
// 1번 | |
if (canCleaning) { | |
map[x][y] = 2; | |
cleaning++; | |
} | |
// 2번 | |
int direction = (d + 3) % 4; // 현재 기준 왼쪽 | |
// 왼쪽 칸 | |
x = r + dir[direction][0]; | |
y = c + dir[direction][1]; | |
if (x < 0 || y < 0 || x >= n || y >= m) break; | |
// a | |
if(map[x][y] == 0) { | |
// 왼쪽 청소 가능 | |
canCleaning = true; | |
d = direction; | |
r = x; | |
c = y; | |
count = 0; | |
} else { | |
// 청소 불가 | |
canCleaning = false; | |
if (count == 4) { | |
// 4방향 모두 확인 | |
// 뒤쪽 방향 | |
int bx = r + dir[(d + 2) % 4][0]; | |
int by = c + dir[(d + 2) % 4][1]; | |
if (map[bx][by] == 1) { // d | |
// 모두 벽 | |
return; | |
} else { // c | |
// 후진 | |
r = bx; | |
c = by; | |
count = 0; | |
} | |
} else { // b | |
/// 왼쪽으로 회전 | |
d = direction; | |
count++; | |
} | |
} | |
} | |
} | |
} |
구글에 쳐보니까 보통 재귀로 풀어서 반복문으로 푼 내 방법으로 해결하는데 꽤 오래 걸렸다. 내일 우테코 코테인데 못풀고 갈까 걱정했지만 정답 맞추고 시험 볼 수 있어서 기분이 좋다.ㅎㅎ
시뮬레이션은 문제 잘 읽어서 상황만 잘 나누면 80% 해결한 것이라고 생각한다.
'Algorithm > Beakjoon' 카테고리의 다른 글
[백준 알고리즘] 구현 - 16236번: 아기상어 (Java) (0) | 2021.11.03 |
---|---|
[백준] 구현 - 15683: 감시 (Java) (0) | 2021.11.03 |
[백준] 동적 계획법 - 2011번: 암호코드 (Java) (0) | 2021.07.25 |
[백준] 동적 계획법 - 11054: 가장 긴 바이토닉 부분 수열 (Java) (0) | 2021.07.19 |
[백준] 동적 계획법 - 11053: 가장 긴 증가하는 부분 수열 (Java) (0) | 2021.07.19 |
댓글