[프로그래머스] PCCP 기출문제 9번

UBIN·2023년 12월 3일
0

문제

주어진 board 배열에서 주어진 위치 (h, w)의 색깔과 동일한 색깔을 가지는 이웃은 몇개인가?

ex)

board = [
	["blue", "red", "orange", "red"], 
	["red", "red", "blue", "orange"], 
    ["blue", "orange", "red", "red"], 
    ["orange", "orange", "red", "blue"]
]
h, w = 1, 1

(h, w) 기준으로 4방향을 검사해서 카운팅하면 된다.

전체코드

def solution(board, h, w):
    answer = 0

    for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        nx, ny = h + dx, w + dy
        if 0 <= nx < len(board) and 0 <= ny < len(board[0]) and board[h][w] == board[nx][ny]:
            answer += 1

    return answer
profile
ubin

0개의 댓글