Python 3 Uniform Cost Search Script to Find Low Cost in Dijkstra Large Graphs Algorithm Full Example Project For Beginners Welcome folks today in this blog post we will be finding lowest cost in dijkstra large graphs algorithm using uniform cost search script in python. All the full source code of the application is shown below.

Get Started

In order to get started you need to make an app.py file and copy paste the following code

app.py

# Python3 implemenatation of above approach

# returns the minimum cost in a vector( if
# there are multiple goal states)
def uniform_cost_search(goal, start):

# minimum cost upto
# goal state from starting
global graph,cost

# create a priority queue
queue = []

# set the answer vector to max value
for i in range(len(goal)):

# insert the starting index
queue.append([0, start])

# map to store visited node
visited = {}

# count
count = 0

# while the queue is not empty
while (len(queue) > 0):

# get the top element of the
queue = sorted(queue)
p = queue[-1]

# pop the element
del queue[-1]

# get the original value
p *= -1

# check if the element is part of
# the goal list
if (p in goal):

# get the position
index = goal.index(p)

# if a new goal is reached
count += 1

# if the cost is less

# pop the element
del queue[-1]

queue = sorted(queue)
if (count == len(goal)):

# check for the non visited nodes
# which are adjacent to present node
if (p not in visited):
for i in range(len(graph[p])):

# value is multiplied by -1 so that
# least priority is at the top
queue.append( [(p + cost[(p, graph[p][i])])* -1, graph[p][i]])

# mark as visited
visited[p] = 1

# main function
if __name__ == '__main__':

# create the graph
graph,cost = [[] for i in range(8)],{}

graph.append(1)
graph.append(3)
graph.append(1)
graph.append(6)
graph.append(4)
graph.append(6)
graph.append(2)
graph.append(5)
graph.append(1)
graph.append(2)
graph.append(6)
graph.append(4)

cost[(0, 1)] = 2
cost[(0, 3)] = 5
cost[(1, 6)] = 1
cost[(3, 1)] = 5
cost[(3, 6)] = 6
cost[(3, 4)] = 2
cost[(2, 1)] = 4
cost[(4, 2)] = 4
cost[(4, 5)] = 3
cost[(5, 2)] = 6
cost[(5, 6)] = 3
cost[(6, 4)] = 7

# goal state
goal = []

# set the goal
# there can be multiple goal states
goal.append(6)

print("Minimum cost from 0 to 6 is = ",answer)

# This code is contributed by mohit kumar 29

Now if you execute the python script by typing the below command as shown below

python app.py 