这道题本不难,难点是在重边。 正常逻辑应该都可以想到 存储顶点与顶点之间的长度的关系,然后dfs从1到n,相当于回溯~
存储的话 第一种解法是字典,稍许麻烦,因为重边的原因,先排序,然后后续进来一致的都否掉;第二种解法是dp二维列表存储,dp[i] [j]代表的是顶点i到顶点j的距离,下次来就是求min。
然后就是常规的dfs。第一种解法遇到的障碍是忽略了可能不在record里面,相当于在利用字典的时候,还是应该提前判断是否在字典中,否则很难检查,遗留大患!!!!
class Solution:
def findShortestPath(self , n , m , graph ):
# write code here
record = {}
graph = sorted(graph, key=lambda x:(x[0], x[2]))
res = 1
for i in range(len(graph)):
node1, node2, length = graph[i]
if node1 not in record:
record[node1] = [[node2, length]]
else:
if record[node1][-1][0] == node2:
continue
else:
record[node1].append([node2, length])
self.max_length = 100000000
sign = {}
def dfs(node, weight):
if node == n:
if weight < self.max_length:
self.max_length = weight
return
if node not in record: # 失败源头!!
return
for i in range(len(record[node])):
res, length = record[node][i]
if res in sign:
continue
sign[res] = 1
dfs(res, weight+length)
sign.pop(res)
dfs(1, 0)
if self.max_length == 100000000:
return -1
return self.max_length
这道题其实和上面的一样,区别是使用了DP来保存i到j的weight。比起字典似乎更加简便。
class Solution:
def findShortestPath(self , n , m , graph ):
dp = []
for i in range(n):
dp.append([float(1000000)]*n)
for i in range(len(graph)):
node1, node2, length = graph[i]
dp[node1-1][node2-1] = min(length, dp[node1-1][node2-1])
sign = {}
self.max_length = 1000000
def dfs(node, weight):
if node == n-1:
if weight < self.max_length:
self.max_length = weight
return
for i in range(n):
if i in sign:
continue
if dp[node][i] != 1000000:
sign[i] = 1
dfs(i, weight+dp[node][i])
sign.pop(i)
else:
continue
dfs(0, 0)
if self.max_length == 1000000:
return -1
return self.max_length