added function shortestPath

This commit is contained in:
Jedrzej Nowak 2019-03-26 17:03:38 +01:00
parent 949c29c9f9
commit 9422d6f45f
11 changed files with 39 additions and 0 deletions

Binary file not shown.

Binary file not shown.

View File

@ -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'),
]

View File

@ -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])