Harsh Shah
def DjikstraAlgorithm(adj, source):
rows, cols, x = adj.shape
visited = {k: False for k in adj[rows]}
distance = {k: float('inf') for k in adj[rows]}
distance[source] = 0
for u in range(rows):
next_dist = min([distance[v] for v in range(rows)
if not visited[v]
])
next_vertex_list = [v for v in range(rows)
if not visited[v]
and distance[v] == next_dist
]
if not next_vertex_list:
break
next_vertex = min(next_vertex_list)
visited[next_vertex] = True
for i in range(cols):
if (adj[next_vertex, i, 0] == 1) and (not visited[i]):
if dist[i] > adj[next_vertex, i, 1] + next_dist:
dist[i] = adj[next_vertex, i, 1]
return distance
def DjikstrasAlgorithm(adjList, source):
vertices = len(adjList.keys())
visited = {k: False for k in range(vertices)}
distance = {k: float('inf') for k in range(vertices)}
distance[source] = 0
for i in adjList:
next_dist = min([distance[v] for v in adjList
if not visited[v]
])
next_vertex_list = [v for v in adjList
if not visited[v]
and distance[v] == next_dist
]
if not next_vertex_list:
break
next_vertex = min(next_vertex_list)
visited[next_vertex] = True
for v in adjList:
for neighbour, weight in v:
if weight + next_dist < distance[neighbour]:
distance[neighbour] = weight + next_dist
return distance
The time complexity for <span class="font-extrabold" key=1> Djikstra's Algorithm </span> in either of the two cases is $O(n^2).$ You can minimise this using <span class="font-extrabold" key=3> Heaps </span> as discussed in further articles. <span class="font-extrabold" key=5> Note: </span> Djikstra's Algorithm does not allow the presence of negative edge weights in the graph.
I write articles on web dev and more specifically on react and next js.