feat: dfs algorithm
This commit is contained in:
parent
e3e6f5d036
commit
c8cce5791c
33
search.py
33
search.py
@ -82,7 +82,38 @@ def depthFirstSearch(problem: SearchProblem):
|
||||
print("Start's successors:", problem.getSuccessors(problem.getStartState()))
|
||||
"""
|
||||
"*** YOUR CODE HERE ***"
|
||||
util.raiseNotDefined()
|
||||
|
||||
actions = []
|
||||
|
||||
curr_state = problem.getStartState()
|
||||
isGoal = problem.isGoalState(curr_state)
|
||||
|
||||
visited = set()
|
||||
stack = util.Stack()
|
||||
|
||||
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)
|
||||
stack.push({
|
||||
'state': (state, direction, cost),
|
||||
'actions': actions
|
||||
})
|
||||
|
||||
# check whether reachable
|
||||
if stack.isEmpty():
|
||||
return []
|
||||
else:
|
||||
obj = stack.pop()
|
||||
(curr_state, direction, cost) = obj['state']
|
||||
actions = obj['actions'] + [ direction ]
|
||||
isGoal = problem.isGoalState(curr_state)
|
||||
|
||||
return actions
|
||||
|
||||
|
||||
|
||||
def breadthFirstSearch(problem: SearchProblem):
|
||||
"""Search the shallowest nodes in the search tree first."""
|
||||
|
||||
Loading…
Reference in New Issue
Block a user