feat: bfs algorithm

This commit is contained in:
snsd0805 2024-03-20 01:27:12 +08:00
parent c8cce5791c
commit 4d6660ab66
Signed by: snsd0805
GPG Key ID: 569349933C77A854

View File

@ -118,7 +118,36 @@ def depthFirstSearch(problem: SearchProblem):
def breadthFirstSearch(problem: SearchProblem):
"""Search the shallowest nodes in the search tree first."""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
actions = []
curr_state = problem.getStartState()
isGoal = problem.isGoalState(curr_state)
visited = set()
queue = util.Queue()
while not isGoal:
# push in the Stack
successors = problem.getSuccessors(curr_state)
for (state, direction, cost) in successors:
if state not in visited:
visited.add(state)
queue.push({
'state': (state, direction, cost),
'actions': actions
})
# check whether reachable
if queue.isEmpty():
return []
else:
obj = queue.pop()
(curr_state, direction, cost) = obj['state']
actions = obj['actions'] + [ direction ]
isGoal = problem.isGoalState(curr_state)
return actions
def uniformCostSearch(problem: SearchProblem):
"""Search the node of least total cost first."""