문제 설명 및 제한사항
아이디어 및 해결 방법
코드
from collections import deque
DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def is_valid(maps, r, c):
return (0 <= r < len(maps)) and (0 <= c < len(maps[0]))
def bfs(maps, r, c, visited):
S = 0
q = deque()
q.append((r, c, int(maps[r][c]))) # (r, c, score)
visited.add((r, c))
while q:
r, c, s = q.popleft()
S += s
for d_r, d_c in DIRECTIONS:
r_new, c_new = r + d_r, c + d_c
if not is_valid(maps, r_new, c_new) or (r_new, c_new) in visited:
continue
if maps[r_new][c_new] != 'X':
q.append((r_new, c_new, int(maps[r_new][c_new])))
visited.add((r_new, c_new))
return S
def solution(maps):
visited = set()
scores = []
for r, row in enumerate(maps):
for c, cell in enumerate(row):
if maps[r][c] == 'X':
continue
if (r, c) in visited:
continue
scores.append(bfs(maps, r, c, visited))
return list(sorted(scores)) if scores else [-1]
Python
복사
출처
프로그래머스 코딩테스트 연습 https://school.programmers.co.kr/learn/challenges