IT/알고리즘

[백준 Python] 14503번 로봇 청소기

와잉 2025. 2. 13. 15:18

백준 파이썬 14503번 로봇 청소기

Gold 5

 

https://www.acmicpc.net/problem/14503

문제가 길어서 어려워보이지만 간단한 구현 문제이다.

import sys
input = sys.stdin.readline
foward = [(-1, 0), (0, 1), (1, 0), (0, -1)]
back = [(1, 0), (0, -1), (-1, 0), (0, 1)]
def func():
    global direction
    direction -= 1
    if direction == -1:
        direction = 3
    tx, ty = foward[direction]
    dx = tx+x
    dy = ty+y
    if lst[dx][dy] == 0 and not clean[dx][dy]:
        q.append((dx, dy,direction))
        return
    else:
        func()
n, m = map(int, input().split())
r, c, d = map(int, input().split())
lst = [list(map(int, input().split())) for _ in range(n)]
clean = [[False]*m for _ in range(n)]
rst = 0
q = [[r,c,d]]
while q:
    x, y, direction = q.pop(0)
    if lst[x][y] == 0 and not clean[x][y]:
        clean[x][y] = True
        rst += 1
    cnt = 0
    for tx, ty in foward:
        dx = x + tx
        dy = y + ty
        if not clean[dx][dy] and lst[dx][dy] == 0:
            cnt += 1
    if cnt > 0:
        func()
    else:
        tx, ty = back[direction]
        dx = tx+x
        dy = ty+y
        if lst[dx][dy] == 0:
            q.append((dx, dy, direction))
        else:
            break
print(rst)

주의할 점은 로봇청소기의 이동 거리를 구하는 것이 아닌 청소 칸의 갯수를 구한다는 점이다.

문제 조건에 맞게 구현에 주었고, 3-3번 조건에 유의해 3번 조건에 대한 내용은 func() 함수를 따로 만들어서 구현해주었다.

+ 1번으로 아예 돌아가기 보다는 바로 3-1번 조건을 수행하게 해준다.

 

반응형

'IT > 알고리즘' 카테고리의 다른 글

[백준 Python] 1717번 집합의 표현  (0) 2025.02.21
[백준 Python] 1958번 LCS 3  (0) 2025.02.17
[백준 Python] 14728번 벼락치기  (0) 2025.02.11
[백준 Python] 19942번 다이어트  (2) 2025.02.06
[백준 Python] 12919번 A와 B 2  (0) 2025.02.06