feat: dfs algorithm

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

View File

@ -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."""