백준 14503 로봇 청소기

문제 링크

알고리즘

  • 구현
  • 시뮬레이션

풀이

문제를 읽어 내려가면서 시키는 대로 구현했다.

핵심은 check 변수를 이용해서 네 방향을 확인하는 것이다. 벽이거나 이미 청소한 구역이라면 check 값에 1을 더해준다.

비교적 쉬운 구현, 시뮬레이션 문제라고 생각한다. 그렇지 않다면 구현을 어려워하는 나로서는 풀기 힘들었을 것이다.


전체 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import sys
input = sys.stdin.readline


n, m = map(int, input().split())
x, y, d = map(int, input().split())

space = []
for i in range(n):
    space.append(list(map(int, input().split())))
    
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

space[x][y] = -1
check = 0

while True:
    nx = x + dx[d-1]
    ny = y + dy[d-1]
    
    if space[nx][ny] == 1 or space[nx][ny] < 0:
        check += 1
        
        if check == 4:
            if d == 0:
                d = 3
            else:
                d -= 1
                
            nx = x - dx[d]
            ny = y - dy[d]
            
            if space[nx][ny] == 1:
                break
            else:
                x -= dx[d]
                y -= dy[d]
                check = 0
        
        else:
            if d == 0:
                d = 3
            else:
                d -= 1
            
            
    else:
        space[nx][ny] = space[x][y] - 1
        x = nx
        y = ny
        check = 0
        
        if d == 0:
            d = 3
        else:
            d -= 1
    
    
count = 0
for i in range(n):
    for j in range(m):
        if space[i][j] < 0:
            count += 1
            
            
print(count)