Notice
Recent Posts
Recent Comments
Link
나의 개발일지
[프로그래머스] Lv.2 무인도 여행 [Python, 파이썬] 본문
- 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/154540
- 🔑 BFS로 연결된 무인도를 탐색
- maps를 순회하면서 무인도를 만나면('X'가 아닌 부분) 현재 위치에서 BFS 탐색을 실시
- BFS를 시작하는 위치와 연결된 무인도들을 모두 탐색하면서 식량 개수를 카운트하고 'X'로 바꾼다.
- BFS 종료 시 식량 개수를 리턴
- 또 maps를 순회하면서 무인도를 찾고 BFS 탐색 반복
from collections import deque
def solution(maps):
def bfs(x, y):
mx, my = [0, 0, 1, -1], [1, -1, 0, 0]
q = deque([(x, y)])
food = int(maps[x][y])
maps[x][y] = 'X'
while q:
x, y = q.popleft()
for i in range(4):
nx, ny = x + mx[i], y + my[i]
if 0 <= nx < len(maps) and 0 <= ny < len(maps[0]) and maps[nx][ny] != 'X':
food += int(maps[nx][ny])
maps[nx][ny] = 'X'
q.append((nx, ny))
return food
answer = []
for i in range(len(maps)):
maps[i] = list(maps[i])
for i in range(len(maps)):
for j in range(len(maps[0])):
if maps[i][j] != 'X':
answer.append(bfs(i, j))
return [-1] if answer == [] else sorted(answer)
'프로그래머스' 카테고리의 다른 글
[프로그래머스] Lv.2 미로 탈출 [Python, 파이썬] (0) | 2024.05.23 |
---|---|
[프로그래머스] Lv.3 섬 연결하기 [Python, 파이썬] (0) | 2024.04.19 |
[프로그래머스] Lv.3 베스트 앨범 [Python, 파이썬] (0) | 2024.02.23 |
[프로그래머스] Lv.2 2개 이하로 다른 비트 [Python, 파이썬] (1) | 2023.12.29 |
[프로그래머스] Lv.3 단속 카메라 [Python, 파이썬] (0) | 2023.12.27 |
Comments