2019-03-25 15:52:35 +01:00
|
|
|
from django.shortcuts import render
|
|
|
|
from django.http import HttpResponse
|
2019-03-26 12:52:23 +01:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
|
|
|
|
import json
|
2019-03-26 18:14:22 +01:00
|
|
|
import math
|
2019-03-25 15:52:35 +01:00
|
|
|
|
|
|
|
# Create your views here.
|
|
|
|
|
|
|
|
|
|
|
|
def index(request):
|
|
|
|
return HttpResponse('It lives!')
|
2019-03-26 12:52:23 +01:00
|
|
|
|
|
|
|
|
|
|
|
@csrf_exempt
|
|
|
|
def classify(request):
|
|
|
|
return HttpResponse(json.load(request))
|
2019-03-26 17:03:38 +01:00
|
|
|
|
2019-03-26 18:14:22 +01:00
|
|
|
|
|
|
|
@csrf_exempt
|
2019-03-26 17:03:38 +01:00
|
|
|
def shortestPath(request):
|
2019-03-26 18:14:22 +01:00
|
|
|
loaded_request = json.load(request)
|
|
|
|
|
|
|
|
graph = loaded_request["graph"]
|
|
|
|
graph = {int(k): v for k, v in graph.items()}
|
|
|
|
for node in graph:
|
|
|
|
graph[node] = {
|
|
|
|
int(k): v for k, v in graph[node].items()}
|
|
|
|
|
|
|
|
start_node = loaded_request["start_node"]
|
|
|
|
dest_node = loaded_request["dest_node"]
|
|
|
|
|
2019-03-26 17:03:38 +01:00
|
|
|
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:
|
2019-03-26 18:14:22 +01:00
|
|
|
p.append(predecessor[current])
|
2019-03-26 17:03:38 +01:00
|
|
|
current = predecessor[current]
|
|
|
|
path[node] = p[::-1]
|
|
|
|
|
2019-03-26 18:14:22 +01:00
|
|
|
return HttpResponse(path[dest_node])
|