solved dfs and bfs

This commit is contained in:
Arjun Patel
2019-02-08 06:09:48 -08:00
parent fc86bf573b
commit cb375ab91d
+34 -33
View File
@@ -87,53 +87,54 @@ def depthFirstSearch(problem):
print("Start's successors:", problem.getSuccessors(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState()))
""" """
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
from game import Directions
from util import Stack from util import Stack
actions, visited, fringe = [], [], Stack()
paths = {}
goal = None
print("Start:", problem.getStartState()) # print("Start:", problem.getStartState())
print("Is the start a goal?", problem.isGoalState(problem.getStartState())) # print("Is the start a goal?", problem.isGoalState(problem.getStartState()))
print("Start's successors:", problem.getSuccessors(problem.getStartState())) # print("Start's successors:", problem.getSuccessors(problem.getStartState()))
fringe.push((problem.getStartState(), '', 0)) visited, fringe = [], Stack()
fringe.push((problem.getStartState(), ()))
while fringe.isEmpty() is False: while fringe.isEmpty() is False:
curr_state = fringe.pop() curr_state = fringe.pop()
if curr_state in visited: if problem.isGoalState(curr_state[0]):
continue return list(curr_state[1])
visited.append(curr_state) if curr_state[0] not in visited:
visited.append(curr_state[0])
if problem.isGoalState(curr_state): for successor in problem.getSuccessors(curr_state[0]):
goal = curr_state added_path = curr_state[1] + (successor[1],) #adding tuples
break
# if curr_state[1]:
# actions.append(curr_state[1])
for successor in problem.getSuccessors(curr_state[0]): if successor[0] not in visited:
fringe.push(successor) fringe.push((successor[0], added_path))
paths[successor[0]] = curr_state
curr_pos = goal
print(goal)
# while curr_pos[0] != problem.getStartState():
# actions.append(curr_pos[1])
# curr_pos = paths[curr_pos[0]]
# print(curr_pos)
# # curr_pos = (problem.getStartState(), '', 0)\
# print(actions)
return [Directions.WEST];
def breadthFirstSearch(problem): def breadthFirstSearch(problem):
"""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() from util import Queue
visited, fringe = [], Queue()
fringe.push((problem.getStartState(), ()))
while fringe.isEmpty() is False:
curr_state = fringe.pop()
if problem.isGoalState(curr_state[0]):
return list(curr_state[1])
if curr_state[0] not in visited:
visited.append(curr_state[0])
for successor in problem.getSuccessors(curr_state[0]):
added_path = curr_state[1] + (successor[1],) #adding tuples
if successor[0] not in visited:
fringe.push((successor[0], added_path))
def uniformCostSearch(problem): def uniformCostSearch(problem):
"""Search the node of least total cost first.""" """Search the node of least total cost first."""