首页 > 试题广场 >

单源最短路

[编程题]单源最短路
  • 热度指数:12145 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
在一个有 n 个点, m 个边的有向图中,已知每条边长,求出 1 到 n 的最短路径,返回 1 到 n 的最短路径值。如果 1 无法到 n ,输出 -1

图中可能有重边,无自环。

数据范围:
示例1

输入

5,5,[[1,2,2],[1,4,5],[2,3,3],[3,5,4],[4,5,5]]

输出

9
示例2

输入

2,1,[[1,2,4]]

输出

4

备注:
两个整数n和m,表示图的顶点数和边数。
一个二维数组,一维3个数据,表示顶点到另外一个顶点的边长度是多少
每条边的长度范围[0,1000]。
注意数据中可能有重边
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param n int 顶点数
# @param m int 边数
# @param graph int二维数组 一维3个数据,表示顶点到另外一个顶点的边长度是多少
# @return int
#
class Solution:
    def findShortestPath(self , n , m , graph ):
        def dijkstra(start, end):
            passed, nopass = [start], [x for x in range(len(adj)) if x != start]
            dis = adj[start]

            while len(nopass):
                idx = nopass[0]
                for i in nopass:
                    if dis[i] < dis[idx]: idx = i

                nopass.remove(idx)
                passed.append(idx)

                for i in nopass:
                    if dis[idx] + adj[idx][i] < dis[i]:
                        dis[i] = dis[idx] + adj[idx][i]
            return dis[end]
        adj = [[float("inf")]*(n) for _ in range(n)]
        for i in range(m):
            adj[graph[i][0]-1][graph[i][1]-1] = min(adj[graph[i][0]-1][graph[i][1]-1], graph[i][2])
        return dijkstra(0, n-1)

编辑于 2021-06-27 22:48:06 回复(0)
class Solution:
    def shortestPath(n, m, graph):
        dp = [-1 for _ in range(len(n) + 1)]
        dp[1] = 0
        minm = float("inf")
        for i in range(2, n+1):
            for j in range(m):
                if graph[j][1] == i and dp[graph[j][0]!=-1:
                    minm = min(minm, graph[j][2]+dp[graph[j][0]])
            dp[i] = minm if minm != float('inf') else -1
        return dp[n]

import sys
while True:
    try:
        line = sys.stdin.readline().rstrip().replace(" ", '')
        nm, graph = line.rstrip("]]").split(",[[")
        n, m = list(map(int, nm.split(",")))
        graph = grpah.split("],[")
        graph = [list(map(int, i.split(",")) for i in graph]
        s = Solution()
        print(s.shortestPath(n, m, graph))

    except:
        break

编辑于 2021-04-11 15:05:21 回复(0)

问题信息

上传者:牛客301499号
难度:
2条回答 4060浏览

热门推荐

通过挑战的用户

查看代码