[LeetCode] 743. Network Delay Time - BFS
글 작성자: _rian
문제 링크 : https://leetcode.com/problems/network-delay-time/
Network Delay Time - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
743. Network Delay Time
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.
Example 1
Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2 Output: 2
Note:
- N will be in the range [1, 100].
- K will be in the range [1, N].
- The length of times will be in the range [1, 6000].
- All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.
풀이
이 문제는 해당 노드에 얼마나 시간이 걸리는지를 확인해야하는 문제였습니다. visited 배열에 시간이 얼마나 걸렸는지를 넣어주는 형식의 문제죠.
Main Idea는 아래와 같습니다.
- BFS를 이용한다
- 배열
t
=> 그 노드를 방문하는데 걸리는 최소 시간. 초반의 모든 원소를float('inf')
(무한을 나타냄)로 시작해서 줄여나가는 방식을 택합니다.
from collections import deque class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: t = [0] + [float('inf')] * N graph = collections.defaultdict(list) q = collections.deque() for u, v, w in times: graph[u].append((v, w)) q.append((0, K)) while q: time, node = q.popleft() if time < t[node]: t[node] = time for v, w in graph[node]: q.append((time + w, v)) mx = max(t) if mx < float('inf'): return mx else: return -1
'알고리즘 Algorithm > PS' 카테고리의 다른 글
[BOJ/백준] 13458. 시험감독 (0) | 2020.10.17 |
---|---|
[LeetCode] 542. 01 Matrix - BFS (0) | 2020.10.15 |
[KickStart] Round F 2020 - ATM Queue (0) | 2020.09.29 |
[백준/BOJ] 4353. 문자열 제곱 (0) | 2020.09.29 |
[백준/BOJ] 4358. 생태학 (0) | 2020.09.29 |
댓글
이 글 공유하기
다른 글
-
[BOJ/백준] 13458. 시험감독
[BOJ/백준] 13458. 시험감독
2020.10.17 -
[LeetCode] 542. 01 Matrix - BFS
[LeetCode] 542. 01 Matrix - BFS
2020.10.15 -
[KickStart] Round F 2020 - ATM Queue
[KickStart] Round F 2020 - ATM Queue
2020.09.29 -
[백준/BOJ] 4353. 문자열 제곱
[백준/BOJ] 4353. 문자열 제곱
2020.09.29
댓글을 사용할 수 없습니다.