반응형
문제
https://school.programmers.co.kr/learn/courses/30/lessons/1844#
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
가중치가 없는 그래프이므로 최단거리를 찾기 위해 BFS 알고리즘을 사용한다
그래프의 최대 크기가 100x100이므로 인접행렬을 통해 그래프를 만든다
코드
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
def bfs(row, col, maps):
q = [[row, col]]
dist = [[-1] * len(maps[0]) for _ in range(len(maps))]
dist[row][col] = 1
while q:
cur = q.pop(0)
for d in range(4):
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
next_row = cur[0] + dy[d]
next_col = cur[1] + dx[d]
if next_row < 0 or next_row >= len(maps) or next_col < 0 or next_col >= len(maps[0]):
continue
if dist[next_row][next_col] == -1 and maps[next_row][next_col] == 1:
q.append([next_row, next_col])
dist[next_row][next_col] = dist[cur[0]][cur[1]] + 1
return dist
def solution(maps):
answer = bfs(0, 0, maps)
return answer[len(maps) - 1][len(maps[0]) - 1]
|
cs |
반응형
'프로그래머스' 카테고리의 다른 글
프로그래머스 - 네트워크 (0) | 2024.06.03 |
---|---|
프로그래머스 - 신고 결과 받기 (0) | 2024.02.10 |
프로그래머스 - 할인 행사 (1) | 2024.02.06 |
프로그래머스 - 완주하지 못한 선수 (0) | 2024.02.02 |
프로그래머스 - 다리를 지나는 트럭 (0) | 2024.02.02 |