From 9b1c13ec7f1867c080e5601618feffe9d23f220f Mon Sep 17 00:00:00 2001 From: AccelerateZ Date: Tue, 22 Sep 2026 10:46:59 +0800 Subject: [PATCH] Add UCS and A* --- search.py | 52 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/search.py b/search.py index 933f847..28201af 100644 --- a/search.py +++ b/search.py @@ -100,10 +100,10 @@ def depthFirstSearch(problem: SearchProblem) -> List[Directions]: currNode, paths = st.pop() if problem.isGoalState(currNode): return paths - if not vis.__contains__(currNode): + if currNode not in vis: vis.add(currNode) for nextNode, path, _ in problem.getSuccessors(currNode): - if not vis.__contains__(nextNode): + if nextNode not in vis: st.push((nextNode, paths + [path])) return [] @@ -119,10 +119,10 @@ def breadthFirstSearch(problem: SearchProblem) -> List[Directions]: currNode, paths = q.pop() if problem.isGoalState(currNode): return paths - if not vis.__contains__(currNode): + if currNode not in vis: vis.add(currNode) for nextNode, path, _ in problem.getSuccessors(currNode): - if not vis.__contains__(nextNode): + if nextNode not in vis: q.push((nextNode, paths + [path])) return [] @@ -130,7 +130,26 @@ def breadthFirstSearch(problem: SearchProblem) -> List[Directions]: def uniformCostSearch(problem: SearchProblem) -> List[Directions]: """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" - util.raiseNotDefined() + pq: util.PriorityQueue = util.PriorityQueue() + vis: set = set() + pq.push( + item=(problem.getStartState(), [], 0), priority=0 + ) # item: state, paths, cost; priority: priority + + while not pq.isEmpty(): + currNode, paths, cost = pq.pop() + if problem.isGoalState(currNode): + return paths + if currNode not in vis: + vis.add(currNode) + for nextNode, path, stepCost in problem.getSuccessors(currNode): + if nextNode not in vis: + pq.push( + item=(nextNode, paths + [path], cost + stepCost), + priority=cost + stepCost, + ) + return [] + def nullHeuristic(state, problem=None) -> float: """ @@ -142,7 +161,28 @@ def nullHeuristic(state, problem=None) -> float: def aStarSearch(problem: SearchProblem, heuristic=nullHeuristic) -> List[Directions]: """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" - util.raiseNotDefined() + + def priorityFunction(item): + state, path, g = item + return g + heuristic(state, problem) + + pqwf: util.PriorityQueueWithFunction = util.PriorityQueueWithFunction( + priorityFunction + ) + vis: set = set() + pqwf.push((problem.getStartState(), [], 0)) + + while not pqwf.isEmpty(): + currNode, paths, cost = pqwf.pop() + if problem.isGoalState(currNode): + return paths + if currNode not in vis: + vis.add(currNode) + for nextNode, path, stepCost in problem.getSuccessors(currNode): + if nextNode not in vis: + pqwf.push((nextNode, paths + [path], cost + stepCost)) + return [] + # Abbreviations bfs = breadthFirstSearch