Skip to content
Snippets Groups Projects
Commit 3c47886a authored by Nour A.'s avatar Nour A.
Browse files

Fixed GBFS: Added __lt__ method to State to support heapq

parent e2907d35
Branches
No related merge requests found
from collections import deque
import heapq
class State: class State:
def __init__(self, position, remaining_rewards): def __init__(self, position, remaining_rewards):
self.position = position # (x, y) self.position = position # (x, y)
self.remaining_rewards = set(remaining_rewards) # {(x1, y1), (x2, y2), ...} self.remaining_rewards = frozenset(remaining_rewards) # {(x1, y1), (x2, y2), ...}
def __lt__(self, other):
return self.position < other.position
def get_neighbors(state, maze): def get_neighbors(state, maze):
x, y = state.position x, y = state.position
...@@ -64,3 +70,65 @@ def print_maze_solution(maze, path): ...@@ -64,3 +70,65 @@ def print_maze_solution(maze, path):
for row in maze_copy: for row in maze_copy:
print("".join(row)) print("".join(row))
single_dfs('test_maze.txt') single_dfs('test_maze.txt')
def single_bfs(file_path):
maze, initial_state = read_maze(file_path)
queue = deque([(initial_state, [])]) # (current state, path)
visited = set()
while queue:
state, path = queue.popleft()
if state.position in visited:
continue
visited.add(state.position)
if is_goal(state):
print_maze_solution(maze, path)
print(f"Path cost: {len(path)}")
print(f"Nodes passed: {len(visited)}")
return path
for move in get_neighbors(state, maze):
new_rewards = state.remaining_rewards - {move} if move in state.remaining_rewards else state.remaining_rewards
new_state = State(move, new_rewards)
queue.append((new_state, path + [move]))
print("Sadly, the mouse is dead :(")
return None
def manhattan_distance(pos1, pos2):
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def single_gbfs(file_path):
maze, initial_state = read_maze(file_path)
goal = next(iter(initial_state.remaining_rewards)) # 1prize,1goal
priority_queue = [(manhattan_distance(initial_state.position, goal), initial_state, [])]
visited = set()
while priority_queue:
_, state, path = heapq.heappop(priority_queue)
if state.position in visited:
continue
visited.add(state.position)
if is_goal(state):
print_maze_solution(maze, path)
print(f"Path cost: {len(path)}")
print(f"Nodes passed: {len(visited)}")
return path
for move in get_neighbors(state, maze):
new_rewards = state.remaining_rewards - {move} if move in state.remaining_rewards else state.remaining_rewards
new_state = State(move, new_rewards)
heapq.heappush(priority_queue, (manhattan_distance(move, goal), new_state, path + [move]))
print("Sadly, the mouse is dead :(")
return None
single_gbfs('test_maze.txt')
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment