BFS Breadth First Search 2.5 marks - Data Structure and Algorithms: + The data structure used in BFS is a queue and a graph.. UCS Uniform Cost Search 2.5 marks - Data structure and Algor
Trang 1INTRODUCTION TO ARTIFICIAL
INTELLIGENCE
MIDTERM REPORT
Lecture: MR BUI THANH HUNG
Student: LÊ DUY KHÁNH – 519K0049
Class: 19K50301 Year: 23
HO CHI MINH CITY, 2022
During the past time, thanks to the dedicated teaching of the teachers of the Faculty of Information Technology, Ton Duc Thang University, I have studied a lot of useful things and accumulated some knowledge to complete my tasks into this report Thank you sincerely.
Trang 2Thanks to Mr.Bui Thanh Hung in charge of Analysis and design algorithm course in this semester for guiding and teaching me enthusiastically and creating condition for me to complete this exercise well Once again I would like to sincerely thank Mr Hung.
The first step into practice, my knowledge is still limited and many surprises Therefore, in the process of compiling, it is difficult to avoid errors, I look forward to receiving your valuable comments and suggestions to improve the report.
Trang 3THE ESSAY HAS BEEN CONDUCTED IN UNIVERSITY
I assure that this is my own product and has been guided by Mr Bui Thanh Hung The research contents, results in this topic are all about honesty and this is the first time my essay published as an academic essay The data in the tables for analysis, comments and evaluation are collected by me from various sources in the reference section
In addition, comments and assessments as well as data from other authors or organizations are also used in the essay but with references and annotations.
If there is any fraud is detected, I ensure my complete responsibility for the contents of my work Ton Duc Thang University is not related to
violations of authority and copyright caused by me during my work process (if any)
Ho Chi Minh city, ngày 04 tháng 04 năm
2022 Student (Sign and provide full name)
Lê Duy Khánh
Trang 4VERIFICATION AND EVALUATION FROM LECTURER Supervisor’s evaluation
_ _ _ _ _ _ _
Ho Chi Minh city, ngày 04 tháng 04 năm 2022
(Sign and provide full name)
Marking lecturer’s evaluation
_ _ _ _ _ _ _
Ho Chi Minh city, ngày 04 tháng 04 năm 2022(Sign and provide full name)
Trang 5In this report, I am going to satisfy these requirements following the contents of final report Answer all the questions in detail, with the knowledge that I’ve collected about computer security, present my own view and decide on solutions that are suitable to solve the requirements of the problem Beside that, I adhere to the rules set forth by the faculty throughout the duration of the report.
TABLE OF CONTENT
Trang 7PROBLEM I (5 marks): Find number of islands by two algorithms:
1 BFS (Breadth First Search) (2.5 marks)
- Data Structure and Algorithms:
+ The data structure used in BFS is a queue and a graph The algorithms makes sure that every node is visited not more than once.
+ BFS follows the following 4 steps:
a) Begin the search algorithm, by knowing the key which is to be searched Once the key/element to be searched is decided the searching begins with the root (source) first.
b) Visit the contiguous unvisited vertex Mark it as visited Display it (if needed) If this is the required key, stop Else, add it in a queue.
c) On the off chance that no neighboring vertex is discovered, expel the first vertex from the Queue.
d) Repeat step 2 and 3 until the queue is empty.
+ The above algorithm is a search algorithm that identifies whether a node exists in the graph We can convert the algorithm to traversal algorithm
to find all the reachable nodes from a given node.
Trang 8- Flowchart of BFS Algorithm:
From Book : Data Structures Through C (A practical approach) By G.S Baluja,
page no 489)
- Code:
from collections import deque
# Below lists detail all eight possible movements from a cell# (top,right, bottom, left, and four diagonal moves)
Trang 9# Function to check if it is safe to go to position (x, y)# from thecurrent position The function returns false if (x, y)# is not valid matrix coordinates or (x, y) represents water or# position (x, y) is already processed.
(mat, x, y, processed):
def isSafe
return (x >= 0 and x < len(processed)) and (y >= 0 and y <
len(processed[0])) and \
mat[x][y] == 1 and not processed[x][y]
# and enqueue each valid movement
for k inrange len( (row)):
# skip if the location is invalid, or already processed,
or has water
if isSafe(mat, x + row[k], y + col[k], processed): # skip if the location is invalid, or it is already # processed, or consists of water
processed[x + row[k]][y + col[k]] = True
q.append((x + row[k], y + col[k]))
(M, N) = (len(mat), len(mat[ ]))0
# stores if a cell is processed or not
processed = [[False for x inrange(N)] for y in range(M)]
Trang 10print('The total number of islands is', countIslands(mat))
-Test: The time complexity of the proposed solution is O(M x N) and requires
O(M x N) extra space, where M and N are dimensions of the matrix.
2 UCS (Uniform Cost Search) (2.5 marks)
- Data structure and Algorithms:
+ A uniform-cost search algorithm is implemented by the priority queue + Uniform-cost search is a searching algorithm used for traversing a weighted tree or graph This algorithm comes into play when a different cost is available for each edge The primary goal of the uniform-cost search
is to find a path to the goal node which has the lowest cumulative cost Uniform-cost search expands nodes according to their path costs form the root node It can be used to solve any graph/tree where the optimal cost is in demand It gives maximum priority to the lowest cumulative cost Uniform cost search is equivalent to BFS algorithm if the path cost of all edges is the same.
Trang 11- Flowchart of UCS algorithm:
Trang 12+ Space Complexity:
Trang 13The same logic is for space complexity so, the worst-case space complexity of Uniform-cost search is O(b1 + [C*/ε]).
PROBLEM II (5 marks): Romania Travelling
1 Greedy Best First Search (2.5 marks)
- Data structure and Algorithms:
+ The greedy best first algorithm is implemented by the priority queue.
+ Greedy best-first search algorithm always selects the path which appears best at that moment It is the combination of depth-first search and breadth-first search algorithms It uses the heuristic function and search Best- first search allows us to take the advantages of both algorithms.
+ With the help of best-first search, at each step, we can choose the most promising node In the best first search algorithm, we expand the node which is closest to the goal node and the closest cost is estimated by heuristic function:
f(n) = g(n).
Were, h(n) = estimated cost from node n to the goal.
- Flowchart of Greedy Best First Search Algorithm:
Trang 14- Code:
# This class represent a graphclass Graph:
# Initialize the class
def init (self, graph_dict=None, directed=True):
self.graph_dict = graph_dict or {}
self.directed = directed
if not directed:
self.make_undirected()
# Create an undirected graph by adding symmetric edges def make_undirected(self):
for a inlist self( graph_dict.keys()):
for (b, dist) inself.graph_dict[a].items():
self.graph_dict.setdefault(b, {})[a] = dist # 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 notself.directed:
self.graph_dict.setdefault(B, {})[A] = distance # Get neighbors or a neighbor
Trang 15if b isNone:
return links
else:
return links.get(b)
# Return a list of nodes in the graph
def nodes(self):
s1 = set([k for k inself.graph_dict.keys()])
s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in
v.items()])
nodes = s1.union(s2)
returnlist(nodes)# This class represent a nodeclass Node: # Initialize the class
def init (self, name:str, parent:str):
self.name = name
self.parent = parent
self.g = 0 # Distance to start node
self.h = 0 # Distance to goal node
self.f = 0 # Total cost
# Compare nodes
def eq (self, other):
returnself.name == other.name
# Sort nodes
def lt (self, other):
returnself.f < other.f
# Print node
def repr (self):
return ('({0},{1})'.format(self.position, self.f))# first searchdef best_first_search(graph, heuristics, start, end):
# Create lists for open nodes and closed nodes
open = []
closed = []
# Create a start node and an goal node
start_node = Node(start, None)
goal_node = Node(end, None)
# Add the start node
open.append(start_node)
# Loop until the open list is empty
while len open( ) > :0
# 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
return path[::- ]1
# Get neighbours
Trang 16for key, value in neighbors.items():
# Create a neighbor node
neighbor = Node(key, current_node)
# Check if the neighbor is in the closed list
if(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# Check if a neighbor should be added to open listdef add_to_open(open, neighbor):
for node inopen:
if (neighbor == node and neighbor.f >= node.f):
graph.connect('Rimnicu Vilcea', 'Pitesti', 97)
graph.connect('Rimnicu Vilcea', 'Craiova', 146)
Trang 17# Run search algorithm
path = best_first_search(graph, heuristics, 'Arad', 'Bucharest') print(path)
print()# Tell python to run main methodif name == " main ":main()
+ Complete: Greedy best-first search is also incomplete, even if the given state space is finite.
+ Optimal: Greedy best first search algorithm is not optimal.
2 A* (2.5 marks)
- Data Structure and Algorithm:
+ A* search is the most commonly known form of best-first search It uses heuristic function h(n), and cost to reach the node n from the start state g(n) It has combined features of UCS and greedy best-first search, by
which it solve the problem efficiently.
+ A* search algorithm finds the shortest path through the search space using the heuristic function This search algorithm expands less
Trang 18search tree and provides optimal result faster A* algorithm is similar to UCS except that it uses g(n)+h(n) instead of g(n).
+ In A* search algorithm, we use search heuristic as well as the cost to reach a fitness number Hence we can combine both costs as following, and this sum is called as a fitness number.
+ f(n) = g(n) + h(n)
f(n): Estimated cost of the cheapest solution
g(n): Cost to reach node n from start state
h(n): Cost to reach from node n to goal node
- Flowchart of A* Algorithm:
Trang 19def push(self, city, cost):
heapq.heappush(self.cities, (cost, city)) def pop(self):
return heapq.heappop(self.cities)[ ]1
def isEmpty(self):
if (self.cities == []):
Trang 20returnFalse
def check(self):
print(self.cities)
class ctNode:
def init (self, city, distance):
self.city = str(city)
self.distance = str(distance)
romania = {}
def makedict():
file = open("romania.txt", 'r')
for string in file:
line = string.split(',')
ct1 = line[ ]0
ct2 = line[ ]1
dist = int(line[ ])2
romania.setdefault(ct1, []).append(ctNode(ct2, dist)) romania.setdefault(ct2, []).append(ctNode(ct1, dist))
def makehuristikdict():
h = {}
with open("romania_sld.txt", 'r') asfile:
for line in file:
line = line.strip().split(",")
node = line[ ].strip()0
sld = int(line[ ].strip())1
for new in romania[current]:
g_cost = distance[current] + int(new.distance) # print(new.city, new.distance, "now : " +
Trang 21printoutput(start, end, path, distance, expandedList)
def printoutput(start, end, path, distance, expandedlist):
print("A* Algorithm for Romania Travelling")
print("\tArad => Bucharest")
print("=======================================================") print("List of cities that are expanded \t\t: " +
str(expandedlist))
print("Total number of cities that are expanded \t\t: " +
str len( (expandedlist)))
print("=======================================================") print("Cities in final path\t: " + str(finalpath))
print("Total number of cities in final path are \t\t\t: " +
+ Time Complexity: The time complexity of A* search algorithm depends
on heuristic function, and the number of nodes expanded is exponential to the depth of solution d So the time complexity is O(b^d), where b is the branching factor.
+ Space Complexity: The space complexity of A* search algorithm is O(b^d)
References:
https://www.javatpoint.com
Trang 22https://www.geeksforgeeks.org https://www.annytab.com https://www.interviewbit.com