입출력 예시
maps | result |
["X591X","X1X5X","X231X", "1XXX1"] | [1, 1, 27] |
["XXX","XXX","XXX"] | [-1] |
나의 코드
from collections import deque
def solution(maps):
nrow, ncol = len(maps), len(maps[0])
def bfs(islands):
scores = []
while islands:
sr, sc = islands.pop()
q = deque()
curr_block = set()
q.append((sr, sc))
curr_block.add((sr, sc))
score = 0
while q:
r, c = q.popleft()
score += int(maps[r][c])
new_pos = [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]
for nr, nc in new_pos:
if (0 <= nr < nrow) and (0 <= nc < ncol) and ((nr, nc) in islands) and ((nr, nc) not in curr_block):
q.append((nr, nc))
curr_block.add((nr, nc))
islands.remove((nr, nc))
scores.append(score)
return scores
islands = set([(r, c) for r in range(nrow) for c in range(ncol) if maps[r][c] != 'X'])
if len(islands) == 0:
return [-1]
else:
return sorted(bfs(islands))
Python
복사