class Solution:
def shortestDistanceAfterQueries(self, n: int, queries: List[List[int]]) -> List[int]:
dp = [0] * n
graph = defaultdict(list)
for i in range(n):
dp[i] = i
ans = []
for start, end in queries:
graph[start].append(end)
dp[end] = min(dp[end], dp[start] + 1)
if end in graph:
for to in graph[end]:
dp[to] = min(dp[to], dp[end] + 1)
for ee in range(end + 1, n - 1):
dp[ee] = min(dp[ee], dp[ee - 1])
if ee in graph:
for to in graph[ee]:
dp[to] = min(dp[to], dp[ee] + 1)
dp[n - 1] = min(dp[n - 1], dp[n - 2] + 1)
ans.append(dp[-1])
return ans
n = 5, queries = [[2,4],[0,2],[0,4]]
답 : [3, 2, 1]
class Solution:
def shortestDistanceAfterQueries(self, n: int, queries: List[List[int]]) -> List[int]:
dp = [0] * n
graph = defaultdict(list)
for i in range(n):
dp[i] = i
ans = []
for start, end in queries:
graph[start].append(end)
dp[end] = min(dp[end], dp[start] + 1)
if end in graph:
for to in graph[end]:
dp[to] = min(dp[to], dp[end] + 1)
for ee in range(end + 1, n - 1):
dp[ee] = min(dp[ee], dp[ee - 1])
if ee in graph:
for to in graph[ee]:
dp[to] = min(dp[to], dp[ee] + 1)
dp[n - 1] = min(dp[n - 1], dp[n - 2] + 1)
ans.append(dp[-1])
return ans