반응형
난이도 - Medium
Intuition
먼저 양방향 그래프를 만들어야 한다. 그다음 dfs를 통해 사과가 있을때마다 2를 더하는 식으로 답을 풀어야 한다.
Code
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
graph = defaultdict(list)
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
def dfs(node, parent):
total_time = child_time = 0
for child in graph[node]:
if child == parent:
continue
child_time = dfs(child, node)
if child_time > 0 or hasApple[child]:
total_time += child_time + 2
return total_time
return dfs(0, -1)
Complexity
Time Complexity: O(n)
Space Complexity: O(n)
반응형
'코딩 알고리즘 문제 > Leetcode' 카테고리의 다른 글
| 16. 3Sum Closest (Array, Two Pointers, Sorting) (0) | 2025.10.24 |
|---|---|
| 380. Insert Delete GetRandom O(1) (Array, Hash Table, Math, Design, Randomized) (0) | 2025.10.24 |
| 122. Best Time to Buy and Sell Stock II (Array, Dynamic Programming, Greedy) (0) | 2025.10.23 |
| 9. Palindrome Number (Math) (0) | 2025.10.23 |
| 2043. Simple Bank System (Array, Hash Table, Design, Simulation) (0) | 2025.10.23 |