added function shortestPath
This commit is contained in:
parent
949c29c9f9
commit
9422d6f45f
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -5,4 +5,5 @@ from . import views
|
||||
urlpatterns = [
|
||||
path('', TemplateView.as_view(template_name='magazine/index.html')),
|
||||
path('classify', views.classify, name='classify'),
|
||||
path('shortestPath', views.shortestPath, name='shortestPath'),
|
||||
]
|
||||
|
@ -14,3 +14,41 @@ def index(request):
|
||||
@csrf_exempt
|
||||
def classify(request):
|
||||
return HttpResponse(json.load(request))
|
||||
|
||||
def shortestPath(request):
|
||||
graph = json.load(request)["graph"]
|
||||
start_node = json.load(request)["start_node"]
|
||||
dest_node = json.load(request)["dest_node"]
|
||||
|
||||
distance = {}
|
||||
predecessor = {}
|
||||
path = {}
|
||||
unseen_nodes = graph.copy()
|
||||
|
||||
for node in graph:
|
||||
distance[node] = math.inf
|
||||
distance[start_node] = 0
|
||||
|
||||
while unseen_nodes:
|
||||
min_node = None
|
||||
for node in unseen_nodes:
|
||||
if min_node is None:
|
||||
min_node = node
|
||||
elif distance[node] < distance[min_node]:
|
||||
min_node = node
|
||||
|
||||
for childNode, weight in graph[min_node].items():
|
||||
if distance[min_node] + weight < distance[childNode]:
|
||||
distance[childNode] = distance[min_node] + weight
|
||||
predecessor[childNode] = min_node
|
||||
unseen_nodes.pop(min_node)
|
||||
|
||||
for node in graph:
|
||||
current = node
|
||||
p = [current + 1]
|
||||
while current != start_node:
|
||||
p.append(predecessor[current] + 1)
|
||||
current = predecessor[current]
|
||||
path[node] = p[::-1]
|
||||
|
||||
return HttpResponse(path[dest_node])
|
Loading…
Reference in New Issue
Block a user