feat: q3 & fix: update visited list in DFS, BFS

This commit is contained in:
snsd0805 2024-03-22 01:53:39 +08:00
parent 4d6660ab66
commit 69a328e196
Signed by: snsd0805
GPG Key ID: 569349933C77A854

View File

@ -88,7 +88,7 @@ def depthFirstSearch(problem: SearchProblem):
curr_state = problem.getStartState()
isGoal = problem.isGoalState(curr_state)
visited = set()
visited = set([curr_state])
stack = util.Stack()
while not isGoal:
@ -96,7 +96,6 @@ def depthFirstSearch(problem: SearchProblem):
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
@ -108,6 +107,7 @@ def depthFirstSearch(problem: SearchProblem):
else:
obj = stack.pop()
(curr_state, direction, cost) = obj['state']
visited.add(curr_state)
actions = obj['actions'] + [ direction ]
isGoal = problem.isGoalState(curr_state)
@ -123,7 +123,7 @@ def breadthFirstSearch(problem: SearchProblem):
curr_state = problem.getStartState()
isGoal = problem.isGoalState(curr_state)
visited = set()
visited = set([curr_state])
queue = util.Queue()
while not isGoal:
@ -152,7 +152,40 @@ def breadthFirstSearch(problem: SearchProblem):
def uniformCostSearch(problem: SearchProblem):
"""Search the node of least total cost first."""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
actions = []
curr_state = problem.getStartState()
isGoal = problem.isGoalState(curr_state)
costs = 0
visited = set([curr_state])
queue = util.PriorityQueue()
while not isGoal:
# push in the P Queue
successors = problem.getSuccessors(curr_state)
for (state, direction, cost) in successors:
if state not in visited:
queue.push({
'state': (state, direction, cost),
'actions': actions,
'costs': costs
}, costs + cost) # if visited this successor node, how much cost will the agent need
# check whether reachable
if queue.isEmpty():
return []
else:
obj = queue.pop()
(curr_state, direction, cost) = obj['state']
visited.add(curr_state)
actions = obj['actions'] + [ direction ]
costs = obj['costs'] + cost
isGoal = problem.isGoalState(curr_state)
return actions
def nullHeuristic(state, problem=None):
"""