Professional Documents
Culture Documents
1. Best-First Search
a. 8 Puzzle Problem Output –
b. Robot Navigation Problem Output –
c. City Distance Problem Output –
d. Code –
# Best-First Search Approach
# 1. 8-Puzzle Problem
# 2. Robot Navigation
# 3. City-Distance Problem
class Puzzle():
# Goal Configuration Of Board
goal = [[1, 2, 3],
[8, 0, 4],
[7, 6, 5]]
# Board Config
board_config = [[2, 3, 4],
[1, 8, 0],
[7, 6, 5]]
open_list.append(new_config)
visited.append(new_config)
print(Fore.RED + "\t\t\tLIST IS DISPLAYED IN ROW MAJOR ORDER\n\n")
print("Initially - ")
# Print Open List
print("Open List - ")
print(open_list)
print()
# Print Closed List
print("Closed List - ")
print(closed_list)
print("\n\n")
while True:
boards_configs.clear()
open_list.remove(new_config)
closed_list.append(new_config)
# Calculate Heuristic Value Of New Board Configurations
heuristic_value = self.calculate_fOfn(new_config)
if heuristic_value == goal_heuristic:
print("Solution Reached !!")
break
boards_configs = self.find_all_configs(new_config)
# Calculating Heuristic Values For All Child Configurations
for i in boards_configs:
visited.append(i)
open_list.append(i)
h = self.calculate_fOfn(i)
objective_values.append(h)
print("Open List - ")
print(open_list)
print("Closed List - ")
print(closed_list)
print("\n\n")
def Start_Puzzle(self):
print("8-Puzzle Problem Using Best First Search\n")
goal_heuristic = self.calculate_fOfn(self.goal)
self.puzzle_start(self.board_config, goal_heuristic)
class Robot():
nav_map = [
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
['-', Fore.BLACK+'#', '-', '-', '-', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', '-'],
['-', Fore.BLACK+'#', Fore.BLACK+'#', '-', '-', '-', Fore.GREEN+'G', '-', '-', Fore.BLACK+'#', '-'],
[Fore.RED+'S', '-', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#',
Fore.BLACK+'#', Fore.BLACK+'#', '-'],
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
]
#Start Position
startx = 0
starty = 3
#Goal Position
goalx = 6
goaly = 2
visited = []
queue = []
new_nav_map = deepcopy(nav_map)
# NAV_MAP [Y][X]
def calManDist(self):
for y in range(5):
for x in range(11):
if self.nav_map[y][x] != Fore.BLACK+'#':
self.new_nav_map[y][x] = abs(self.goalx - x) + abs(self.goaly - y)
position = [self.startx, self.starty]
self.queue.append((self.new_nav_map[self.starty][self.startx], position))
def calPossibleMoves(self):
x = self.startx
y = self.starty
if self.isSafe(x+1, y) == True:
position = [x+1, y]
if self.new_nav_map[y][x+1] != Fore.BLACK+'#' and ((self.new_nav_map[y][x+1], position)) not in self.visited:
self.queue.append((self.new_nav_map[y][x+1], position))
if self.isSafe(x-1, y) == True:
position = [x - 1, y]
if self.new_nav_map[y][x-1] != Fore.BLACK+'#' and ((self.new_nav_map[y][x-1], position)) not in self.visited:
self.queue.append((self.new_nav_map[y][x-1], position))
self.queue.sort(reverse=True)
def Start_Navigation(self):
print("Initial Map - ")
self.print_map(self.nav_map)
print("\n\n\n")
self.calManDist()
print("After Calculating Manhanttan Distance - ")
self.print_map(self.new_nav_map)
print("\n\n\n")
while (self.queue):
input()
next = self.queue.pop()
print("Selecting Next Position : X = " + str(next[1][0]) + " , Y = " + str(next[1][1]))
print("Heuristic Value = " + str(next[0]))
print()
if next[1][0] == self.goalx and next[1][1] == self.goaly:
print(f"Goal State Reached")
exit(1)
if next[1] == [self.startx, self.starty]: self.nav_map[next[1]
[1]][next[1][0]] = Fore.BLUE+'S'
else:
self.nav_map[next[1][1]][next[1][0]] = Fore.BLUE+str(self.new_nav_map[next[1][1]][next[1][0]])
self.visited.append(next)
self.startx = next[1][0]
self.starty = next[1][1]
self.calPossibleMoves()
self.print_map(self.nav_map)
print(' ')
class City_Distance():
class Graph:
def init (self, graph_dict=None, directed=True):
self.graph_dict = graph_dict or {}
self.directed = directed
if not directed:
self.make_undirected()
# Add a link from A and B of given distance, and also add the inverse link if the graph is undirected
def connect(self, A, B, distance=1):
self.graph_dict.setdefault(A, {})[B] = distance
if not self.directed:
self.graph_dict.setdefault(B, {})[A] = distance
# Display Graph
def display_graph(self): print(Fore.YELLOW+"\n\t\t\
tTHE GRAPH IS - \n") for key in self.graph_dict:
print(Fore.CYAN+key, Fore.WHITE+' -> ', self.graph_dict[key])
# This class represent a node
class Node:
# Initialize the class
def init (self, name: str, parent: str):
self.name = name
self.parent = parent
self.g = 0 # Distance from start node
self.h = 0 # Distance to goal node
self.f = 0 # Total cost
# Compare nodes
def eq (self, other):
return self.name == other.name
# Sort nodes
def lt (self, other):
return self.f < other.f
# Print node
def repr (self):
return ('({0},{1})'.format(self.position, self.f))
# Best-first search
def best_first_search(self, graph, heuristics, start, end):
# Sort the open list to get the node with the lowest cost first
open.sort()
# Get the node with the lowest cost
current_node = open.pop(0)
# Add the current node to the closed list
closed.append(current_node)
# Get neighbours
neighbors = graph.get(current_node.name)
# Loop neighbors
for key, value in neighbors.items():
# Create a neighbor node
neighbor = self.Node(key, current_node)
# Check if the neighbor is in the closed list
if (neighbor in closed):
continue
# Calculate cost to goal
neighbor.h = heuristics.get(neighbor.name)
neighbor.f = neighbor.h
# Check if neighbor is in open list and if it has a lower f value
if (self.add_to_open(open, neighbor) == True):
# Everything is green, add neighbor to open list
open.append(neighbor)
# Return None, no path is found
return None
def start(self):
# Create a graph
graph = self.Graph()
# Create graph connections (Actual distance)
graph.connect('Oradea', 'Zerind', 71)
graph.connect('Oradea', 'Sibiu', 151)
graph.connect('Zerind', 'Arad', 75)
graph.connect('Arad', 'Sibiu', 140)
graph.connect('Arad', 'Timisoara', 118)
graph.connect('Timisoara', 'Lugoj', 111)
graph.connect('Lugoj', 'Mehadia', 70)
graph.connect('Mehadia', 'Drobeta', 75)
graph.connect('Drobeta', 'Craiova', 120)
graph.connect('Craiova', 'Pitesti', 138)
graph.connect('Craiova', 'Rimnicu Vilcea', 146)
graph.connect('Sibiu', 'Fagaras', 99)
graph.connect('Fagaras', 'Bucharest', 211)
graph.connect('Sibiu', 'Rimnicu Vilcea', 80)
graph.connect('Rimnicu Vilcea', 'Pitesti', 97)
graph.connect('Pitesti', 'Bucharest', 101)
graph.connect('Bucharest', 'Giurgui', 90)
# Display Graph
graph.display_graph()
if(choice == 1):
temp =
Puzzle()
temp.Start_Puzzle()
elif(choice == 2):
temp = Robot()
temp.Start_Navigation()
elif(choice == 3):
temp = City_Distance()
temp.start()
2. A* Algorithm
a. 8 Puzzle Problem Output –
b. Robot Navigation Problem Output –
c. City Distance Problem Output –
d. Code –
# A* Approach
# 1. 8-Puzzle Problem
# 2. Robot Navigation
# 3. City-Distance Problem
class Puzzle():
# Goal Configuration Of Board
goal = [[1, 2, 3],
[8, 0, 4],
[7, 6, 5]]
# Board Config
board_config = [[2, 3, 4],
[1, 8, 0],
[7, 6, 5]]
# Number Of Steps
steps = 0
open_list.append(new_config)
visited.append(new_config)
while True:
self.steps += 1
boards_configs.clear()
open_list.remove(new_config)
closed_list.append(new_config)
# Calculate Heuristic Value Of New Board Configurations
heuristic_value = self.calculate_fOfn(new_config)
if heuristic_value == goal_heuristic:
print("Solution Reached !!")
print(f"\nIn {self.steps} Steps\n")
break
boards_configs = self.find_all_configs(new_config)
# Calculating Heuristic Values For All Child Configurations
for i in boards_configs:
visited.append(i)
open_list.append(i)
h = self.calculate_fOfn(i)
objective_values.append(h)
print("Open List - ")
print(open_list)
print("Closed List - ")
print(closed_list)
print("\n\n")
def Start_Puzzle(self):
print("8-Puzzle Problem Using Best First Search\n")
goal_heuristic = self.calculate_fOfn(self.goal)
self.puzzle_start(self.board_config, goal_heuristic)
class Robot():
nav_map = [
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
['-', Fore.BLACK+'#', '-', '-', '-', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', '-'],
['-', Fore.BLACK+'#', Fore.BLACK+'#', '-', '-', '-', Fore.GREEN+'G', '-', '-', Fore.BLACK+'#', '-'],
[Fore.RED+'S', '-', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#',
Fore.BLACK+'#', Fore.BLACK+'#', '-'],
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
]
#Start Position
startx = 0
starty = 3
#Goal Position
goalx = 6
goaly = 2
visited = []
queue = []
new_nav_map = [
[11, 11, 9, 11, 11, 11, 11, 13, 4, 5, 6],
[9, Fore.BLACK+'#', 11, 11, 11, Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', 5],
[7, Fore.BLACK+'#', Fore.BLACK+'#', 3, 11, 11, 11, 1, 2, Fore.BLACK+'#', 4],
[7, 7, Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#', Fore.BLACK+'#',
Fore.BLACK+'#', 5],
[9, 9, 9, 9, 9, 9, 9, 11, 4, 5, 6],
]
position = [startx, starty] queue.append((new_nav_map[starty]
[startx], position))
def calPossibleMoves(self):
x = self.startx
y = self.starty
if self.isSafe(x+1, y) == True:
position = [x + 1, y]
if self.new_nav_map[y][x+1] != Fore.BLACK+'#' and ((self.new_nav_map[y][x+1], position)) not in self.visited:
self.queue.append((self.new_nav_map[y][x+1], position))
if self.isSafe(x-1, y) == True:
position = [x - 1, y]
if self.new_nav_map[y][x-1] != Fore.BLACK+'#' and ((self.new_nav_map[y][x-1], position)) not in self.visited:
self.queue.append((self.new_nav_map[y][x-1], position))
self.queue.sort(reverse=True)
def Start_Navigation(self):
print("Initial Map - ")
self.print_map(self.nav_map)
print("\n\n\n")
#self.calManDist()
print("After Calculating Manhanttan Distance - ")
self.print_map(self.new_nav_map)
print("\n\n\n")
startx1 = self.startx
starty1 = self.starty
while (self.queue):
input()
print(f"Queue = {self.queue}")
next = self.queue.pop(0)
print("Selecting Next Position : X = " + str(next[1][0]) + " , Y = " + str(next[1][1]))
print("Heuristic Value = " + str(next[0]))
print()
if next[1][0] == self.goalx and next[1][1] == self.goaly:
print(f"Goal State Reached")
exit(1)
if next[1] == [startx1, starty1]: self.nav_map[next[1][1]]
[next[1][0]] = Fore.BLUE + 'S'
else:
self.nav_map[next[1][1]][next[1][0]] = Fore.BLUE + str(self.new_nav_map[next[1][1]][next[1][0]])
self.visited.append(next)
self.startx = next[1][0]
self.starty = next[1][1]
self.calPossibleMoves()
self.print_map(self.nav_map)
print(' ')
class City_Distance():
class Graph:
def init (self, graph_dict=None, directed=True):
self.graph_dict = graph_dict or {}
self.directed = directed
if not directed:
self.make_undirected()
# Add a link from A and B of given distance, and also add the inverse link if the graph is undirected
def connect(self, A, B, distance=1):
self.graph_dict.setdefault(A, {})[B] = distance
if not self.directed:
self.graph_dict.setdefault(B, {})[A] = distance
# Compare nodes
def eq (self, other):
return self.name == other.name
# Sort nodes
def lt (self, other):
return self.f < other.f
# Print node
def repr (self):
return ('({0},{1})'.format(self.position, self.f))
# Best-first search
def best_first_search(self, graph, heuristics, start, end):
# Sort the open list to get the node with the lowest cost first
open.sort()
# Get the node with the lowest cost
current_node = open.pop(0)
# Add the current node to the closed list
closed.append(current_node)
def start(self):
# Create a graph
graph = self.Graph()
# Create graph connections (Actual distance)
graph.connect('Oradea', 'Zerind', 71)
graph.connect('Oradea', 'Sibiu', 151)
graph.connect('Zerind', 'Arad', 75)
graph.connect('Arad', 'Sibiu', 140)
graph.connect('Arad', 'Timisoara', 118)
graph.connect('Timisoara', 'Lugoj', 111)
graph.connect('Lugoj', 'Mehadia', 70)
graph.connect('Mehadia', 'Drobeta', 75)
graph.connect('Drobeta', 'Craiova', 120)
graph.connect('Craiova', 'Pitesti', 138)
graph.connect('Craiova', 'Rimnicu Vilcea', 146)
graph.connect('Sibiu', 'Fagaras', 99)
graph.connect('Fagaras', 'Bucharest', 211)
graph.connect('Sibiu', 'Rimnicu Vilcea', 80)
graph.connect('Rimnicu Vilcea', 'Pitesti', 97)
graph.connect('Pitesti', 'Bucharest', 101)
graph.connect('Bucharest', 'Giurgui', 90)
if(choice == 1):
temp = Puzzle() temp.Start_Puzzle()
elif(choice == 3):
temp = City_Distance() temp.start()