打卡记录
T 秒后青蛙的位置(DFS)
链接
class Solution:def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:g = [[] for _ in range(n + 1)]for x, y in edges:g[x].append(y)g[y].append(x)g[1].append(0)ans = 0def dfs(x, fa, time, prod):if x == target and (time == 0 or len(g[x]) == 1):nonlocal ansans = 1 / prodreturn Trueif x == target or time == 0: return Falsefor y in g[x]:if y == fa: continueif dfs(y, x, time - 1, prod * (len(g[x]) - 1)): return Truereturn Falsedfs(1, 0, t, 1)return ans
树上最大得分和路径(DFS)
链接
class Solution:def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:n = len(amount)g = [[] for _ in range(n)]for x, y in edges:g[x].append(y)g[y].append(x)g[0].append(-1)bob_time = [n] * ndef dfs_bob(x: int, fa: int, t: int) -> bool:if x == 0:bob_time[x] = treturn Truefor y in g[x]:if y != fa and dfs_bob(y, x, t + 1):bob_time[x] = treturn Truereturn Falsedfs_bob(bob, -1, 0)ans = -infdef dfs_alice(x: int, fa: int, alice_time: int, tot: int) -> None:if alice_time < bob_time[x]:tot += amount[x]elif alice_time == bob_time[x]:tot += amount[x] // 2if len(g[x]) == 1:nonlocal ansans = max(ans, tot)returnfor y in g[x]:if y != fa:dfs_alice(y, x, alice_time + 1, tot)dfs_alice(0, -1, 0, 0)return ans