Add DFS and BFS
This commit is contained in:
@@ -17,9 +17,11 @@ In search.py, you will implement generic search algorithms which are called by
|
||||
Pacman agents (in searchAgents.py).
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
|
||||
import util
|
||||
from game import Directions
|
||||
from typing import List
|
||||
|
||||
|
||||
class SearchProblem:
|
||||
"""
|
||||
@@ -90,12 +92,40 @@ def depthFirstSearch(problem: SearchProblem) -> List[Directions]:
|
||||
print("Start's successors:", problem.getSuccessors(problem.getStartState()))
|
||||
"""
|
||||
"*** 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]:
|
||||
"""Search the shallowest nodes in the search tree first."""
|
||||
"*** 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]:
|
||||
"""Search the node of least total cost first."""
|
||||
|
||||
Reference in New Issue
Block a user