저는 파이썬에서 구현 된 기본적인 선형 최단 경로 알고리즘을 가지고 있습니다. 다양한 사이트에 따르면, 이것은 this, this 및 this을 비롯한 지시 된 비순환 적 그래프에서만 작동합니다. 그러나 이것이 왜 그런지 나는 알지 못합니다.선형 최단 경로 알고리즘이 왜 무향 순환 그래프에 대해 작동하지 않습니까?
나는주기와 무향 가장자리가있는 그래프에 대해 알고리즘을 테스트 해 보았지만 정상적으로 작동했습니다.
질문 : 왜 선형 최단 경로 알고리즘이 비 방향성 순환 그래프에서 작동하지 않습니까? 사이드 질문, 이 알고리즘의 이름은 무엇입니까? 참고로
, 여기에 내가 알고리즘에 대해 쓴 코드는 다음과 같습니다 베타에 의해 요청으로, 여기에 위상 일종이다 :
def shortestPath(start, end, graph):
# First, topologically sort the graph, to determine which order to traverse it in
sorted = toplogicalSort(start, graph)
# Get ready to store the current weight of each node's path, and their predecessor
weights = [0] + [float('inf')] * (len(graph) - 1)
predecessor = [0] * len(graph)
# Next, relaxes all edges in the order of sorted nodes
for node in sorted:
for neighbour in graph[node]:
# Checks if it would be cheaper to take this path, as opposed to the last path
if weights[neighbour[0]] > weights[node] + neighbour[1]:
# If it is, then adjust the weight and predecessor
weights[neighbour[0]] = weights[node] + neighbour[1]
predecessor[neighbour[0]] = node
# Returns the shortest path to the end
path = [end]
while path[len(path) - 1] != start:
path.append(predecessor[path[len(path) - 1]])
return path[::-1]
편집
# Toplogically sorts the graph given, starting from the start point given.
def toplogicalSort(start, graph):
# Runs a DFS on all nodes connected to the starting node in the graph
def DFS(start):
for node in graph[start]:
if not node[0] in checked:
checked[node[0]] = True
DFS(node[0])
finish.append(start)
# Stores the finish point of all nodes in the graph, and a boolean stating if they have been checked
finish, checked = [], {}
DFS(start)
# Reverses the order of the sort, to get a proper topology; then returns
return finish[::-1]
첫 번째 참조의 알고리즘은 그래프의 위상 정렬을 포함합니다. 사이클을 포함하는 그래프로 어떻게 할 수 있습니까? – Beta
질문에 방법을 추가했습니다. – Cisplatin
"어떻게 구현합니까?" 질문은 순환 적 그래프를 위상 적으로 정렬하는 것이 무엇을 의미한다고 생각합니까? – user2357112