카테고리 없음

[프로그래머스 특강]1-3. 시뮬레이션 예제 - 청소로봇3

흑요석s 2023. 8. 25. 14:14

방법 1

def solution(board, k):
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]
    n = len(board)
    see = 1
    r, c = 0, 0
    cnt = 0
    while k>0:
        k -= 1
        nr = r + dr[see]
        nc = c + dc[see]
        if 0 <= nr < n and 0 <= nc < n and board[nr][nc] != 1:  #외곽지대와 장애물 
            r = nr
            r = nc
        else :
            see = (see + 1) % 4 #외곽지대 장애물 만나면 90도 회전

    return [r, c]
        


print(solution([[0, 0, 0, 0, 0],
                [0, 1, 1, 0, 0],
                [0, 0, 0, 0, 0],
                [1, 0, 1, 0, 1],
                [0, 0, 0, 0, 0]], 10))

 

방법 2 

def solution(board, k):
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]
    n = len(board)
    see = 1
    r, c = 0, 0
    cnt = 0
    while cnt < k:
        cnt += 1
        nr = r + dr[see]
        nc = c + dc[see]
        if nr < 0 or nr >=n or nc < 0 or nc >= n or board[nr][nc] == 1 : #막혀있다면 회전
            see = (see + 1) % 4
            continue
        r = nr
        c = nc

    return [r, c]
        


print(solution([[0, 0, 0, 0, 0],
                [0, 1, 1, 0, 0],
                [0, 0, 0, 0, 0],
                [1, 0, 1, 0, 1],
                [0, 0, 0, 0, 0]], 10))