Add DFS and BFS

This commit is contained in:
AccelerateZ
2026-09-21 23:40:24 +08:00
parent c25aa0942b
commit 26741aec49
+33 -3
View File
@@ -17,9 +17,11 @@ In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py). Pacman agents (in searchAgents.py).
""" """
from typing import List
import util import util
from game import Directions from game import Directions
from typing import List
class SearchProblem: class SearchProblem:
""" """
@@ -90,12 +92,40 @@ def depthFirstSearch(problem: SearchProblem) -> List[Directions]:
print("Start's successors:", problem.getSuccessors(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState()))
""" """
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
util.raiseNotDefined() st: util.Stack = util.Stack()
vis: set = set()
st.push((problem.getStartState(), [])) # current node, path
while not st.isEmpty():
currNode, paths = st.pop()
if problem.isGoalState(currNode):
return paths
if not vis.__contains__(currNode):
vis.add(currNode)
for nextNode, path, _ in problem.getSuccessors(currNode):
if not vis.__contains__(nextNode):
st.push((nextNode, paths + [path]))
return []
def breadthFirstSearch(problem: SearchProblem) -> List[Directions]: def breadthFirstSearch(problem: SearchProblem) -> List[Directions]:
"""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() q: util.Queue = util.Queue()
vis: set = set()
q.push((problem.getStartState(), [])) # current node, path
while not q.isEmpty():
currNode, paths = q.pop()
if problem.isGoalState(currNode):
return paths
if not vis.__contains__(currNode):
vis.add(currNode)
for nextNode, path, _ in problem.getSuccessors(currNode):
if not vis.__contains__(nextNode):
q.push((nextNode, paths + [path]))
return []
def uniformCostSearch(problem: SearchProblem) -> List[Directions]: def uniformCostSearch(problem: SearchProblem) -> List[Directions]:
"""Search the node of least total cost first.""" """Search the node of least total cost first."""