Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

0|Page

Assignment

Course Title: Artificial Intelligence


Course Code: CSE-3205
Topic: Creating a map, finding Shortest Path and map coloring using different algorithms.

Submitted To :

Dr Tania Islam
Assistant Professor
Department of Computer Science & Engineering
University of Barishal

Submitted By:

Subrina Jahan Meem


Roll : 20CSE012
Session 2019-20
Year: 3rd
Semester: 2nd
Submission Date: 10/05/2024
1|Page

Map from Home (N Hossain Avenue) to University of Barisal


 Distance given in meter

Applying BFS on map to find Shortest Path


Dequeue Queue

N Hossain Avenue

Bels Park Police Line Barisal Club


N Hossain Avenue

Bels Park Police Line Barisal Club Chandmari

Barisal Club Chandmari Banglabazar


Police Line

Chandmari Banglabazar Planet Park


Barisal Club

Chandmari Banglabazar Planet Park Band Road

Banglabazar Planet Park Band Road Shadhinota park


2|Page

Planet Park Band Road Shadhinota park

Band Road Shadhinota park Amtola

Shadhinota park Amtola

Amtola Sagordi

Sagordi Rupatoli

Rupatoli Tol Ghor

Tol Ghor Dapdapia Bridge

Dapdapia Bridge University of Barisal

Fig: Shortest path Using BFS


Shortest path for BFS:
N Hossain Avenue-> Bels Park-> Chandmari-> Band Road-> Amtola-> Sagordi-> Rupatoli-> Tol
Ghor-> Dapdapia Bridge-> University of Barisal
3|Page

Applying DFS on Map to find Shortest Path


Stack

N Hossain
Avenue

N Hossain Barisal
Avenue Club

N Hossain Barisal Planet


Avenue Club Park

N Hossain Barisal Planet Band


Avenue Club Park Road

N Hossain Barisal Planet Band Amtola


Avenue Club Park Road

N Hossain Barisal Planet Band Amtola Sagordi


Avenue Club Park Road

N Hossain Barisal Planet Band Amtola Sagordi Rupatoli


Avenue Club Park Road

N Hossain Barisal Planet Band Amtola Sagordi Rupatoli Tol


Avenue Club Park Road Ghor

N Hossain Barisal Planet Band Amtola Sagordi Rupatoli Tol Dapdapia


Avenue Club Park Road Ghor Bridge

N Hossain Barisal Planet Band Amtola Sagordi Rupatoli Tol Dapdapia University
Avenue Club Park Road Ghor Bridge Of Barisal
4|Page

Fig: Shortest path Using DFS


Shortest path for DFS:
N Hossain Avenue-> Barisal Club-> Planet Park-> Band Road-> Amtola-> Sagordi-> Rupatoli-> Tol
Ghor-> Dapdapia Bridge-> University Of Barisal

Applying UCS on Map to find Shortest Path


Total Distance Dequeue Queue
N Hossain Avenue

0 N Hossain Avenue Bels Park Police Line Barisal Club

650 Bels Park Police Line Barisal Club Chandmari

290 Police Line Barisal Club Chandmari Banglabazar

250 Barisal Club Chandmari Banglabazar Planet Park

1150 Chandmari Banglabazar Planet Park Band Road

550 Banglabazar Planet Park Band Road Shadhinota park


5|Page

800 Planet Park Band Road Shadhinota park

1300 Band Road Shadhinota park Amtola

1300 Shadhinota park Amtola

1550 Amtola Sagordi

1950 Sagordi Rupatoli

3250 Rupatoli Tol Ghor

4750 Tol Ghor Dapdapia Bridge

5700 Dapdapia Bridge University of Barisal

Fig: Shortest path Using UCS


Shortest path for UCS:
N Hossain Avenue-> Police line-> Banglabazar-> Shadhinota park-> Amtola-> Sagordi-> Rupatoli
-> Tol Ghor-> Dapdapia Bridge-> University of Barisal
6|Page

Conclusion:
 Breadth-First Search (BFS) can also find the shortest path, but it may use more memory.
BFS has a time complexity of O(V + E) and a space complexity of O(V), where V is the
number of vertices and E is the number of edges.
 Depth-First Search (DFS) isn't ideal for shortest path finding because it can get stuck and
doesn't ensure the shortest route. DFS has a time complexity of O(V + E) and a space
complexity of O(V).
 Uniform Cost Search (UCS) is the best option for finding the shortest path because it can
handle different weights on paths and always guarantees the shortest route. UCS has a
time complexity of O((V + E) log V) and a space complexity of O(V).

Map Coloring
 The variables are (nodes):
N Hossain Avenue, Police Line, Bels Park, Barisal Club, Banglabazar, Chandmari, Planet
Park, Shadhinota Park, Band Road, Amtola, Sagordi, Rupatoli, Tol Ghor, Dapdapia Bridge,
University of Barisal.
 Domains: {Red, Green, Blue}
 Constraints: adjacent regions must have different colors.

Fig: Map Coloring


7|Page

Backtracking Search
 Starting with node N Hossain Avenue and coloring them as visited. Staring with red. If
there is no further node then backtrack to previous node. Keep moving to the last
unvisited node.

 No further path from University of Barisal. So, Backtrack to Amtola. Next Unvisited node
is Band Road.

 N Hossain avenue have one unvisited node Barisal club. No move to that node until no
unvisited node left.
8|Page

Fig: Backtracking Search

Forward Checking
 Keeping track of remaining legal values for unassigned variables and terminating search
when any variable has no legal values.
Lets take the nodes as-
N Hossain Avenue(Ave), Police Line(PL), Bels Park(BP), Barisal Club(BC), Banglabazar(BL),
Chandmari(CM), Planet Park(PP), Shadhinota Park(SP), Band Road(BR), Amtola(AL),
Sagordi(SD), Rupatoli(RT), Tol Ghor(TG), Dapdapia Bridge(DB), University of Barisal(BU).

AVE PL BP BC BL CM PP SP BR AL SD RT TG DB BU
9|Page

ARC Consistency
Arc consistency is the simplest form of propagation makes each pair of variables. It detects
failure earlier than forward checking.

Conclusion:
 Backtracking search is versatile and can handle a wide range of problems efficiently, but
it may suffer from slow performance in some cases.
 Forward checking is efficient for pruning the search space but may not be suitable for all
types of problems.
 Arc consistency is beneficial for enforcing global consistency between pairs of variables
but may require significant computational resources.
It's essential to consider these factors when selecting the most appropriate algorithm for a
given problem instance.

Implementation:
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import networkx as nx
from collections import deque

nodes = {
'N Hossain Avenue': (300, 50),
'Police line': (220, 160),
'Barisal Club': (400, 120),
'Bels park': (300, 165),
'Planet Park': (400, 280),
'Band Road': (360, 380),
'Chandmari': (320, 330),
'Amtola': (120, 450),
'Banglabazar': (150, 280),
'Shadhinota park': (110, 380),
'Sagordi': (110, 500),
'Rupatoli': (105, 600),
'Tol Ghor': (140, 700),
'Dapdapia Bridge': (300, 700),
'University of Barisal': (400, 700)
}
10 | P a g e

edges = [
('N Hossain Avenue', 'Bels park', {'weight': 650}),
('N Hossain Avenue', 'Police line', {'weight': 290}),
('N Hossain Avenue', 'Barisal Club', {'weight': 250}),
('Barisal Club', 'Planet Park', {'weight': 550}),
('Planet Park', 'Band Road', {'weight': 500}),
('Bels park', 'Chandmari', {'weight': 500}),
('Chandmari', 'Band Road', {'weight': 400}),
('Police line', 'Banglabazar', {'weight': 260}),
('Banglabazar', 'Shadhinota park', {'weight': 1000}),
('Shadhinota park', 'Amtola', {'weight': 400}),
('Amtola', 'Sagordi', {'weight': 400}),
('Band Road', 'Amtola', {'weight': 1400}),
('Sagordi', 'Rupatoli', {'weight': 1300}),
('Rupatoli', 'Tol Ghor', {'weight': 1500}),
('Tol Ghor', 'Dapdapia Bridge', {'weight': 850}),
('Dapdapia Bridge', 'University of Barisal', {'weight': 950})
]

graph = {
'N Hossain Avenue': [('Bels park', 650), ('Police line', 290), ('Barisal
Club', 250)],
'Police line': [('N Hossain Avenue', 290), ('Banglabazar', 260)],
'Barisal Club': [('N Hossain Avenue', 250), ('Planet Park', 550)],
'Bels park': [('N Hossain Avenue', 650), ('Chandmari', 500)],
'Planet Park': [('Barisal Club', 550), ('Band Road', 500)],
'Band Road': [('Planet Park', 500), ('Chandmari', 400), ('Amtola',
1400)],
'Chandmari': [('Bels park', 500), ('Band Road', 400)],
'Amtola': [('Band Road', 1400), ('Sagordi', 400)],
'Banglabazar': [('Police line', 260), ('Shadhinota park', 1000)],
'Shadhinota park': [('Banglabazar', 1000), ('Amtola', 400)],
'Sagordi': [('Amtola', 400), ('Rupatoli', 1300)],
'Rupatoli': [('Sagordi', 1300), ('Tol Ghor', 1500)],
'Tol Ghor': [('Rupatoli', 1500), ('Dapdapia Bridge', 850)],
'Dapdapia Bridge': [('Tol Ghor', 850), ('University of Barisal', 950)],
'University of Barisal': [('Dapdapia Bridge', 950)]
}

def color_graph(graph):
colors = {}
for node in graph:
used_colors = set(colors.get(neigh) for neigh, _ in graph[node])
11 | P a g e

for color in ['red', 'green', 'blue']:


if color not in used_colors:
colors[node] = color
break
return colors

def forward_checking(graph, colors, node, color):


for neighbor, _ in graph[node]:
if colors.get(neighbor) == color:
return False
return True

def map_coloring(graph):
colors = {}
for node in graph:
for color in ['red', 'green', 'blue']:
if forward_checking(graph, colors, node, color):
colors[node] = color
break
return colors
def arc_consistency(graph):
def constraint(node1_color, node2_color):
return node1_color != node2_color

def AC_3(csp):
queue = []
for Xi in csp['variables']:
for Xj in csp['neighbors'][Xi]:
queue.append((Xi, Xj))

while queue:
Xi, Xj = queue.pop(0)
revised = False
for x in csp['domains'][Xi]:
if all(not constraint(x, y) for y in csp['domains'][Xj]):
csp['domains'][Xi].remove(x)
revised = True
if revised:
if not csp['domains'][Xi]:
return False
for Xk in csp['neighbors'][Xi]:
if Xk != Xj:
queue.append((Xk, Xi))
12 | P a g e

return True

csp = {
'variables': list(graph.keys()),
'domains': {node: ['red', 'green', 'blue'] for node in graph},
'neighbors': {node: [neighbor for neighbor, _ in graph[node]] for
node in graph},
}
return AC_3(csp)

def bfs(graph, start, goal):


queue = [(start, [start])]
while queue:
(node, path) = queue.pop(0)
for next_node, _ in graph[node]:
if next_node not in path:
if next_node == goal:
return path + [next_node]
else:
queue.append((next_node, path + [next_node]))

def dfs(graph, start, goal):


stack = [(start, [start])]
while stack:
(node, path) = stack.pop()
for next_node, _ in graph[node]:
if next_node not in path:
if next_node == goal:
return path + [next_node]
else:
stack.append((next_node, path + [next_node]))

def ucs(graph, start, goal):


queue = [(0, start, [start])]
while queue:
(cost, node, path) = queue.pop(0)
if node == goal:
return path
for next_node, next_cost in graph[node]:
if next_node not in path:
queue.append((cost + next_cost, next_node, path +
[next_node]))
13 | P a g e

queue = sorted(queue, key=lambda x: x[0])

root = tk.Tk()
root.title("Shortest Path Finder")
root.geometry("400x700")
fig, ax = plt.subplots()
ax.set_title('N Hossain Avenue to University of Barisal\n Subrina Jahan Meem
(20CSE012)')

G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
ax.invert_yaxis()

pos = {node: (x, y) for node, (x, y) in nodes.items()}


nx.draw(G, pos, ax=ax, with_labels=True, node_size=500,
node_color='lightblue', font_size=12)

edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}


nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels,
font_color='black', font_size=12)

canvas = FigureCanvasTkAgg(fig, master=root)


canvas_widget = canvas.get_tk_widget()
canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

def highlight_path(path, color):


for i in range(len(path) - 1):
edge = (path[i], path[i+1])
nx.draw_networkx_edges(G, pos, edgelist=[edge], width=2,
edge_color=color)
nx.draw_networkx_nodes(G, pos, nodelist=[path[i], path[i+1]],
node_color=color, node_size=500)
plt.draw()

def bfs_click():
shortest_path = bfs(graph, 'N Hossain Avenue', 'University of Barisal')
highlight_path(shortest_path, 'orange')

def dfs_click():
shortest_path = dfs(graph, 'N Hossain Avenue', 'University of Barisal')
highlight_path(shortest_path, 'red')
14 | P a g e

def ucs_click():
shortest_path = ucs(graph, 'N Hossain Avenue', 'University of Barisal')
highlight_path(shortest_path, 'yellow')

def color_click():
colors = color_graph(graph)
node_colors = [colors.get(node, 'white') for node in graph]
nx.draw(G, pos, ax=ax, with_labels=True, node_size=500, font_size=12,
node_color=node_colors)
plt.draw()

def map_coloring_click():
colors = map_coloring(graph)
node_colors = [colors.get(node, 'white') for node in graph]
nx.draw(G, pos, ax=ax, with_labels=True, node_size=500, font_size=12,
node_color=node_colors)
plt.draw()

def arc_consistency_click():
arc_consistency(graph)
colors = color_graph(graph)
node_colors = [colors.get(node, 'white') for node in graph]
nx.draw(G, pos, ax=ax, with_labels=True, node_size=500, font_size=12,
node_color=node_colors)
plt.draw()

for algo, command, color in [("BFS", bfs_click, 'orange'), ("DFS", dfs_click,


'red'), ("UCS", ucs_click, 'yellow'), ("Color", color_click, 'blue'), ("Map
Coloring", map_coloring_click, 'green'), ("Arc Consistency",
arc_consistency_click, 'purple')]:
button = tk.Button(root, text=algo, command=command)
button.pack(side=tk.LEFT, padx=5, pady=5)

root.mainloop()

You might also like