我是Ruby的新手,我正在尝试在给定adj_matrix(2D数组)的情况下找到从原点节点到目标节点的最短路径。
假设:忽略直接路径可能性
我的代码目前使用以下描述/逻辑。
但是,如果我改为另一个adj_matrix来测试其他测试用例,它将不会返回最佳路径。
还有其他更好的方法吗?
def find_way(adj_matrix,origin,dest) result = [origin]
destPath = checkDestinationPath(adj_matrix,origin) #[1,2,3,4]
originPath = checkOriginPath(adj_matrix,dest) #[6,7,9]
value = nil
distance = 0
for i in 0..originPath.length-1
element = originPath[i] #6,7,9
path = checkOriginPath(adj_matrix,element) #find which vertex go the element Eg:6-[1,4,7,8,9] 7-[1,6,8] 9-[4,5,6,8]
allVertexInElement = checkFound(destPath,path) #stores common vertex that are also in destPath (Eg: 4)
if allVertexInElement.length != 0
for j in 0..allVertexInElement.length-1
currVertex = allVertexInElement[j] #4
a = checkDestinationPath(adj_matrix,currVertex)
distance = adj_matrix[origin][currVertex] #8
if currVertex == dest #exit entire for loop
distance = adj_matrix[origin][currVertex] + adj_matrix[currVertex][dest]
value = "#{currVertex}" + "," + "#{element}"
break
else
commonVertex = checkFound2(originPath,a) # 6,9
for k in 0..commonVertex.length-1 #2 or more possible path: 0-4-6-8 vs 0-4-9-8
current = commonVertex[k] #6,9
distance += adj_matrix[currVertex][current]
distance += adj_matrix[current][dest]
if k == 0
shortestDist = distance #20
value = "#{currVertex}" + "," + "#{element}" # 4,6
else
if distance < shortestDist
shortestDist = distance #16
value = "#{currVertex}" + "," + "#{element}" #4,9
end
end
distance = adj_matrix[origin][currVertex] #reset: 8
end
end
end
end
end
values = value.split(",")
values.each do |x|
result << x.to_i #4,9
end
result << dest #8
return result #[0,4,9,8]
端