一:DFS
class Solution(object):
def numOfMinutes(self, n, headID, manager, informTime):
subordinates = collections.defaultdict(list)
self.res = 0
for i, v in enumerate(manager):
subordinates[v].append(i)
def dfs(manager, time):
self.res = max(self.res, time)
for subordinate in subordinates[manager]:
dfs(subordinate, time + informTime[manager])
dfs(headID, 0)
return self.res
二:BFS
class Solution(object):
def numOfMinutes(self, n, headID, manager, informTime):
q = [[headID,0]]
graph = collections.defaultdict(list)
for i,v in enumerate(manager):
graph[v].append(i)
ans = -1
while q:
empID, tot_time = q.pop(0)
ans = max(ans, tot_time)
for adj in graph[empID]:
q.append([adj, tot_time + informTime[empID]])
return ans