feat: bfs algorithm
This commit is contained in:
parent
c8cce5791c
commit
4d6660ab66
31
search.py
31
search.py
@ -118,7 +118,36 @@ def depthFirstSearch(problem: SearchProblem):
|
|||||||
def breadthFirstSearch(problem: SearchProblem):
|
def breadthFirstSearch(problem: SearchProblem):
|
||||||
"""Search the shallowest nodes in the search tree first."""
|
"""Search the shallowest nodes in the search tree first."""
|
||||||
"*** YOUR CODE HERE ***"
|
"*** 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):
|
def uniformCostSearch(problem: SearchProblem):
|
||||||
"""Search the node of least total cost first."""
|
"""Search the node of least total cost first."""
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user