leetcode.K站中转(python)

开始准备用dfs深度搜索,发现n=100,dfs可能会超时,即使用了剪枝。

python 复制代码
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        length = k + 2
        ans = float('inf')
        rec = []
        vis = [True]*n
        edge = defaultdict(list)
        for f, t, p in flights:
            edge[f].append([t, p])

        def dfs(node, spend):
            nonlocal ans
            rec.append(node)
            vis[node] = False
            if node == dst:
                ans = min(ans, spend)
            elif len(rec) < length:
                for nex, p in edge[node]:
                    if not vis[nex]: continue
                    dfs(nex, spend + p)
            rec.pop()
            vis[node] = True
        dfs(src, 0)
        return ans if ans != float('inf') else -1

理所当然的想用bfs,n=100肯定不会超时,谁知道题目针对,这次内存超了。因为题目中

  • 0 <= flights.length <= (n * (n - 1) / 2)

相当于100*99/2,大概5000条路线呗。这就超了???

python 复制代码
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        edge = defaultdict(dict)
        for f, t, p in flights:
            edge[f][t] = p
        qu = deque()
        ans = float('inf')
        qu.append([src, 0, -1])
        while qu:
            node, spend, num = qu.popleft()
            if num > k:continue
            if node == dst:
                ans = min( ans, spend )
                continue
            for nex in edge[node]:
                qu.append([nex, spend + edge[node][nex], num + 1])
        return ans if ans != float('inf') else -1

看见大佬的优化过程,叹为观止。

使用最小堆,每次弹出列表中最小花费的路径,利用steps避免走成一个环。发现我之前的问题,应该就是走进一个环中,导致数据增多,内存超了。

python 复制代码
import heapq as pq
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        edge = defaultdict(dict)
        for f, t, p in flights:
            edge[f][t] = p
        qu = [[0, src, -1]]
        pq.heapify(qu)
        steps = [k+1]*n
        while qu:
            spend, node, num = pq.heappop(qu)
            if steps[node] <= num:continue
            steps[node] = num
            if node == dst:
                return spend
            for nex in edge[node]:
                pq.heappush(qu, [spend + edge[node][nex], nex, num + 1])
        return -1

下面是官方题解,使用dp。

使用dp动态规划算法,设dp【t】【i】,表示转到第t站,从src到达i所需的最小花费数;

那么dp【t】【i】 = min(dp【t】【i】,dp【t-1】【j】+cost【j】【i】),遍历所有路线。

python 复制代码
class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        dp = [[float('inf')]*(n) for _ in range(k+2)]
        dp[0][src] = 0
        ans = float('inf')
        for t in range(1, k+2):
            for j, i, p in flights:
                dp[t][i] = min(dp[t][i], dp[t-1][j] + p)
                if i == dst: ans = min (ans, dp[t][i])
        return ans if ans != float('inf') else -1

这个动态规划,内核也就是bfs。第一次只更新了从src出发到达的节点。这个方法稍稍不如bfs,因为每一步都走了一些不能走的点。

相关推荐
cui_ruicheng7 小时前
LangChain 应用开发(十二):Agent 中间件与内置中间件
人工智能·python·中间件·langchain
zx_741484817 小时前
【Python 入门】Python 正则表达式零基础讲解:基础语法 + 元字符 + 常用案例
python·正则表达式
weixin199701080167 小时前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
2601_957883847 小时前
2026年8月:华硕笔记本维修相关信息
python·电脑
lzqrzpt7 小时前
临沂LED驱动电源工程选型与直销工厂评估标准解析
python·单片机·嵌入式硬件
老郑聊AI业财智造8 小时前
给大模型装上“金融之眼”:Kronos-Report的量化预测架构与技术全景剖析
人工智能·python·深度学习·语言模型·金融·架构·软件工程
问天_观心8 小时前
深入学习Transformer(一)
人工智能·python·深度学习·神经网络·学习·transformer
雷帝木木8 小时前
DVC数据版本控制实战:让训练数据像代码一样可追溯
人工智能·python·深度学习·机器学习
月光船幽幽8 小时前
五层探针的哲学跃迁
人工智能·python
阿图灵8 小时前
OpenCV 轮廓与属性:查找轮廓、面积周长、形状拟合与点测试
图像处理·人工智能·python·opencv·计算机视觉·轮廓