Day36力扣打卡

打卡记录

T 秒后青蛙的位置(DFS)

链接

python 复制代码
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 = 0
        def dfs(x, fa, time, prod):
            if x == target and (time == 0 or len(g[x]) == 1):
                nonlocal ans
                ans = 1 / prod
                return True
            if x == target or time == 0: return False
            for y in g[x]:
                if y == fa: continue
                if dfs(y, x, time - 1, prod * (len(g[x]) - 1)): return True
            return False
        dfs(1, 0, t, 1)
        return ans

树上最大得分和路径(DFS)

链接

python 复制代码
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] * n
        def dfs_bob(x: int, fa: int, t: int) -> bool:
            if x == 0:
                bob_time[x] = t
                return True
            for y in g[x]:
                if y != fa and dfs_bob(y, x, t + 1):
                    bob_time[x] = t
                    return True
            return False
        dfs_bob(bob, -1, 0)

        ans = -inf
        def 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] // 2
            if len(g[x]) == 1:
                nonlocal ans
                ans = max(ans, tot)
                return
            for y in g[x]:
                if y != fa:
                    dfs_alice(y, x, alice_time + 1, tot)
        dfs_alice(0, -1, 0, 0)
        return ans
相关推荐
数据智能老司机1 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v2 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机3 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i4 小时前
django中的FBV 和 CBV
python·django
c8i4 小时前
python中的闭包和装饰器
python
惯导马工4 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农5 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了6 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo6 小时前
322:零钱兑换(三种方法)
算法
这里有鱼汤7 小时前
小白必看:QMT里的miniQMT入门教程
后端·python