Lab3 - Uninformed Search Algorithms (BFS)
Lab3 - Uninformed Search Algorithms (BFS)
# BFS implementation
def bfs(start, goal):
# Queue to maintain paths
queue = deque([[start]])
visited = set() # Set to track visited nodes
while queue:
path = queue.popleft() # Get the first path from the
queue
node = path[-1] # Get the last node in the path
def is_valid_state(state):
"""Check if a state is valid."""
m_left, c_left, m_right, c_right, _ = state
def get_successors(state):
"""Generate all possible valid successors from the current
state."""
m_left, c_left, m_right, c_right, boat = state
successors = []
moves = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] # Possible
movements
while queue:
current_state, path = queue.popleft()
if current_state in visited:
continue
visited.add(current_state)
path = path + [current_state]
# Explore successors
for successor in get_successors(current_state):
if successor not in visited:
queue.append((successor, path))
return None
Python Deque:
while queue:
current, path = queue.popleft()
x, y = current
if current == goal:
return path + [current]
if current in visited:
continue
visited.add(current)
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = x + dx, y + dy
if 0 <= nx < len(maze) and 0 <= ny < len(maze[0])
and maze[nx][ny] != 1:
queue.append(((nx, ny), path + [current]))
return None
fig, ax = plt.subplots()
ax.imshow(maze, cmap=cmap, norm=norm)
if path:
for node in path[1:-1]:
ax.scatter(node[1], node[0], color='green',
marker='o')
ax.legend()
plt.show()
# Example maze
maze = np.array([
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
])
start = (0, 0)
goal = (4, 4)