0% found this document useful (0 votes)
15 views

AI Lab Report 2

Uploaded by

Tahsin Ahmmed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

AI Lab Report 2

Uploaded by

Tahsin Ahmmed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Green University of Bangladesh

Department of Computer Science and Engineering (CSE)


Faculty of Sciences and Engineering
Semester: (Spring, Year:2024), B.Sc. in CSE (Day)

Lab Report NO 02

Course Title: Artificial Intelligence Lab


Course Code: CSE 316 Section: 212-D5

Lab Experiment Name: Implementing BFS and DFS in Python.


Student Details

Name ID
1. Tahsin Ahmmed 212002063

Lab Experiment Date : 12-03 -2024


Submission Date : 19-03 -2024
Course Teacher’s Name : Sheikh Fazle Rabbi

Lab Report Status


Marks: ………………………………… Signature:.....................
Comments:.............................................. Date:..............................
1. TITLE OF THE LAB REPORT EXPERIMENT
Implementing BFS and DFS in Python.
2. OBJECTIVES/AIM :

 To implement Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms in


Python.
 To gain a deeper understanding of graph traversal techniques by implementing two
fundamental algorithms.
 To compare the traversal order, time complexity, and applications of DFS and BFS to
understand their differences and similarities.
 To apply DFS and BFS algorithms to traverse a given graph and observe their traversal
paths.
 To analyze the traversal results to draw insights into the behavior and performance of
DFS and BFS in graph traversal tasks.

3. PROCEDURE / ANALYSIS / DESIGN

BFS:
 Define a function create_node(x, y, level) to create a node with coordinates (x, y) and a
given level.
 Implement a function is_valid(graph, x, y) to check if the given coordinates (x, y) are
valid within the graph boundaries and represent an accessible cell.
 Implement the Breadth-First Search (BFS) algorithm bfs(graph, source, goal) to find the
shortest path from a given source node to a goal node within the graph. It utilizes a queue
to explore neighboring nodes level by level until reaching the goal.
 In the main block, define the graph and source and goal states. Then, execute the BFS
algorithm to find the shortest path. Print the number of moves required if the goal is
found; otherwise, indicate that the goal cannot be reached from the starting block.
DFS:
 Define a function create_node(x, y, level) to create a node with coordinates (x, y) and a
given level.
 Implement a function is_valid(graph, x, y) to check if the given coordinates (x, y) are
valid within the graph boundaries and represent an accessible cell.
 Implement the Depth-First Search (DFS) algorithm dfs(graph, source, goal) to find a path
from a given source node to a goal node within the graph. It utilizes a stack to explore
neighboring nodes in a depth-first manner until reaching the goal or exhausting all
possible paths.
 In the main block, define the graph and source and goal states. Then, execute the DFS
algorithm to find a path to the goal. If the goal is reached, print the number of moves
required; otherwise, indicate that the goal cannot be reached.
4. IMPLEMENTATION
BFS:
1. def create_node(x, y, level):
2. # print((x,y,level))

3.

4. return (x, y, level)

5.

6.

7. def is_valid(graph, x, y):


8. # print(graph)
9. N = len(graph)
10. # print(N)
11. return 0 <= x < N and 0 <= y < N and graph[x][y] == 1

12.

13.

14. def bfs(graph, source, goal):


15. directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Up, down, left, right
16. N = len(graph)

17.

18. queue = [source]


19. # print([source])
20. visited = set([source[:2]])
21. # print(set([source[:2]]))

22.

23. while queue:


24. u = queue.pop(0)
25. # print(u)
26. # print(u[:2])
27. # print(u[2])

28.

29. if u[:2] == goal:


30. # print(u[2])
31. return u[2] # Return the level (number of moves)

32.

33. for dx, dy in directions:


34. v_x = u[0] + dx
35.

36. """
37. v_x = u[0] + dx: This line calculates

38.

39. the new x-coordinate of the neighboring node


40. v by adding the current x-coordinate u[0]

41.

42. with the change in x-coordinate dx.

43.

44. """

45.

46. # print(u[0])
47. # print(dx)
48. # print(v_x)
49. v_y = u[1] + dy
50. # print(v_y)
51. # print(v_x, v_y)

52.

53. if is_valid(graph, v_x, v_y) and (v_x, v_y) not in visited:


54. visited.add((v_x, v_y))
55. new_node = create_node(v_x, v_y, u[2] + 1)
56. queue.append(new_node)

57.

58. return -1 # Goal not reachable

59.

60. if __name__ == "__main__":


61. graph = [
62. [0, 0, 1, 0, 1],
63. [0, 1, 1, 1, 1],
64. [0, 1, 0, 0, 1],
65. [1, 1, 0, 1, 1],
66. [1, 0, 0, 0, 1]
67. ]

68.

69. source = (0, 2, 0) # source state (x, y, level)


70. goal = (4, 4) # goal state (x, y)

71.
72. level = bfs(graph, source, goal)
73. #print(level)

74.

75. if level != -1:


76. print("Goal found!")
77. print("Number of moves required:", level)
78. else:
79. print("Sorry!!! Goal can not be reached from starting block or source block")

DFS:
1. def create_node(x, y, level):
2. return (x, y, level)
3.
4. def is_valid(graph, x, y):
5. N = len(graph)
6. return 0 <= x < N and 0 <= y < N and graph[x][y] == 1
7.
8. def dfs(graph, source, goal):
9. directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Up, down, left, right
10. N = len(graph)
11.
12. stack = [source]
13. visited = set([source[:2]])
14.
15. while stack:
16. x, y, level = stack.pop(len(stack)-1)
17.
18. if (x, y) == goal:
19. print("Goal achieved!")
20. print("Number of moves required:", level)
21. return
22.
23. for dx, dy in directions:
24. v_x = x + dx
25. v_y = y + dy
26.
27. if is_valid(graph, v_x, v_y) and (v_x, v_y) not in visited:
28. visited.add((v_x, v_y)) # Mark as visited
29. new_node = create_node(v_x, v_y, level + 1) # Increment level for th
30. stack.append(new_node) # Add neighboring node with incremented level
31.
32. print("Goal not reachable")
33.
34. if __name__ == "__main__":
35. graph = [
36. [0, 0, 1, 0, 1],
37. [0, 1, 1, 1, 1],
38. [0, 1, 0, 0, 1],
39. [1, 1, 0, 1, 1],
40. [1, 0, 0, 0, 1]
41. ]
42.
43. source = (0, 2, 0) # source state (x, y, level)
44. goal = (4, 4) # goal state (x, y)
45.
46. dfs(graph, source, goal)

5. TEST RESULT / OUTPUT

BFS:

DFS:

6. ANALYSIS AND DISCUSSION:

In the discussion section, we compare and contrast Depth-First Search (DFS) and Breadth-First
Search (BFS) algorithms implemented in Python. We note that DFS explores as far as possible
along each branch before backtracking, resulting in a more memory-efficient approach but
potentially leading to longer paths. On the other hand, BFS explores all neighbors of a node
before moving on to the next level, ensuring the shortest path is found but requiring more
memory. We discuss the implications of these differences in various applications, such as
puzzle-solving or network routing, where one algorithm may be preferred over the other based
on memory constraints or the need for optimal solutions. Additionally, we emphasize the
importance of understanding the characteristics and trade-offs of each algorithm in selecting the
appropriate one for a given problem domain.

You might also like