title: "[프로그래머스] 무인도 여행 Python 파이썬 해설 (Level 2) - 이도훈"
cleanUrl: "programmers/154540"
description: "프로그래머스 Level 2 문제 [무인도 여행]의 풀이를 정리합니다."
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]
프로그래머스 코딩테스트 연습 https://school.programmers.co.kr/learn/challenges