Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

PRACTICAL - 3

Aim :
Write a program to implement DFS (for 8 puzzle problem or Water jug Problem or any AI search
Problem).

8-Puzzle Problem:-

Code:
# Define the 8-puzzle problem state
class PuzzleState:
def __init__(self, state, parent, action, depth):
self.state = state
self.parent = parent
self.action = action
self.depth = depth

def __str__(self):
return str(self.state)

def __eq__(self, other):


return self.state == other.state

def __hash__(self):
return hash(str(self.state))

# Define the 8-puzzle problem


class PuzzleProblem:
def __init__(self, initial_state, goal_state):
self.initial_state = initial_state
self.goal_state = goal_state

201310132060 Ms. Ritika Lohiya


def get_successors(self, state):
successors = []
blank_pos = state.state.index(0)
if blank_pos not in [0, 1, 2]: # Move up
new_state = state.state[:]
new_state[blank_pos], new_state[blank_pos-3] = new_state[blank_pos-3],
new_state[blank_pos]
successors.append(PuzzleState(new_state, state, "Up", state.depth+1))
if blank_pos not in [6, 7, 8]: # Move down
new_state = state.state[:]
new_state[blank_pos], new_state[blank_pos+3] = new_state[blank_pos+3],
new_state[blank_pos]
successors.append(PuzzleState(new_state, state, "Down", state.depth+1))
if blank_pos not in [0, 3, 6]: # Move left
new_state = state.state[:]
new_state[blank_pos], new_state[blank_pos-1] = new_state[blank_pos-1],
new_state[blank_pos]
successors.append(PuzzleState(new_state, state, "Left", state.depth+1))
if blank_pos not in [2, 5, 8]: # Move right
new_state = state.state[:]
new_state[blank_pos], new_state[blank_pos+1] = new_state[blank_pos+1],
new_state[blank_pos]
successors.append(PuzzleState(new_state, state, "Right", state.depth+1))
return successors

def goal_test(self, state):


return state.state == self.goal_state

# Define the depth-first search algorithm


def dfs(problem):
explored = set()
stack = [problem.initial_state]
while stack:
state = stack.pop()
201310132060 Ms. Ritika Lohiya
if problem.goal_test(state):
return state
explored.add(state)
successors = problem.get_successors(state)
for successor in successors:
if successor not in explored and successor not in stack:
stack.append(successor)
return None

# Define the initial and goal states for the 8-puzzle problem
initial_state = [1, 0, 2,
7, 8, 3,
6, 5, 4]

goal_state = [1, 2, 3,
8, 0, 4,
7, 6, 5]

# Create a new PuzzleProblem object and solve it using DFS


problem = PuzzleProblem(PuzzleState(initial_state, None, None, 0), goal_state)
solution = dfs(problem)

# Print the solution


if solution is None:
print("No solution found.")
else:
path = []
while solution.parent is not None:
path.append(solution.action)
solution = solution.parent
path.reverse()
print("Moves:", path)

201310132060 Ms. Ritika Lohiya


Output:-

201310132060 Ms. Ritika Lohiya

You might also like