네트워크 지연 시간
'네트워크 지연 시간' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'네트워크 지연 시간' 문제는 고급 그래프 섹션의 핵심 과제입니다.
이 구현은 Python의 쉬운 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
네트워크 지연 시간에 대한 논리 흐름 시각화.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
네트워크 지연 시간에 대한 문제 설명을 주의 깊게 읽으십시오.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
1부터 n까지 레이블이 지정된 n개의 노드로 구성된 네트워크가 제공됩니다. 또한 방향이 지정된 간선으로 이동 시간 목록인 시간이 제공됩니다. times[i] = [ui, vi, wi], 여기서 ui는 소스 노드, vi는 대상 노드, wi는 신호가 소스에서 대상으로 이동하는 데 걸리는 시간입니다.
주어진 노드 k에서 신호를 보냅니다. n개 노드 모두가 신호를 수신하는 데 걸리는 최소 시간을 반환합니다. n개의 노드 모두가 신호를 수신하는 것이 불가능하면 -1을 반환합니다.
networkDelayTime(times: List[List[int]], n: int, k: int) -> int 함수를 작성하세요.
- •1 <= k <= n <= 100
- •1 <= len(times) <= 6000
- •times[i].length == 3
- •1 <= ui, vi <= n
- •ui != vi
- •0 <= wi <= 100
- •All the pairs (ui, vi) are unique
예
times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
2
The signal starts at node 2. It reaches 1 and 3 in 1 unit of time, and 4 in 2 units of time.
times = [[1,2,1]], n = 2, k = 1
1
Signal reaches node 2 from node 1 in 1 unit of time.
times = [[1,2,1]], n = 2, k = 2
-1
Signal starts at node 2, but there is no path from node 2 to node 1. So node 1 never receives it.
Need a Hint?
Edge Cases to Watch
- 빈 입력 구조
- 단일 요소 입력
- 큰 수치 범위
해결할 준비가 되셨나요?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
인터뷰 통찰력 및 변형
복잡성 분석 분석
왜 시간인가?: Directly evaluates all possibilities.
왜 우주인가?: Uses standard local memory.
왜 시간인가?: Optimized paths reduce total operations.
왜 우주인가?: May trade memory for speed.
최적화된 솔루션 Python 코드
최적화된 솔루션 Python 코드
def network_delay_time_opt(times, n, k):
return network_delay_time_brute(times, n, k)무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
import heapq, collections
def network_delay_time_brute(times, n, k):
edges = collections.defaultdict(list)
for u, v, w in times: edges[u].append((v, w))
min_heap = [(0, k)]
visit = {}
while min_heap:
w1, n1 = heapq.heappop(min_heap)
if n1 in visit: continue
visit[n1] = w1
for n2, w2 in edges[n1]:
if n2 not in visit: heapq.heappush(min_heap, (w1 + w2, n2))
return max(visit.values()) if len(visit) == n else -1Algorithm Pattern Checklist
When dealing with Advanced Graphs data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
표준 고급 그래프 문제 속성이 적용됩니다.
관련 질문
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
권장 Python 리소스
관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.
Python Datetime
Python에서 날짜, 시간, 시간대 및 계산을 처리하는 방법을 알아보세요. 날짜/시간 및 timedelta를 사용하여 형식 지정, 구문 분석 및 산술을 마스터합니다.
Python에서 문자열을 날짜/시간으로 구문 분석하는 방법(strptime)
Python에서 문자열을 날짜/시간 객체로 변환하는 방법을 알아보세요. strptime 방법을 익히고, 날짜 문자열을 구문 분석하고, 시간대를 처리하고, 형식 오류를 방지하세요.
Python DateTime 형식 지정 치트 시트
datetime, strftime 및 strptime을 사용하여 Python에서 날짜와 시간을 구문 분석하고 형식을 지정하는 방법을 알아보세요.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.