You are on page 1of 3

Name: Khemal Desai

Roll No: I008

Batch A1

Code:
State = {

   'farmer': 'left',

   'wolf': 'left',

   'goat': 'left',

   'cabbage': 'left'

goal_state = {

   'farmer': 'right',

   'wolf': 'right',

   'goat': 'right',

   'cabbage': 'right'

actions = [

   {'farmer': 'left', 'wolf': 'left'},

   {'farmer': 'left', 'goat': 'left'},

   {'farmer': 'left', 'cabbage': 'left'},

   {'farmer': 'left'},

   {'farmer': 'right', 'wolf': 'right'},

   {'farmer': 'right', 'goat': 'right'},

   {'farmer': 'right', 'cabbage': 'right'},

   {'farmer': 'right'}

 
def is_valid(state):

   # The wolf and goat can't be left alone together

   if state['wolf'] == state['goat'] and state['farmer'] != state['wolf']:

       return False

   # The goat and cabbage can't be left alone together

   if state['goat'] == state['cabbage'] and state['farmer'] != state['goat']:

       return False

   return True

def apply_action(state, action):

   new_state = state.copy()

   # Move the farmer

   new_state['farmer'] = action['farmer']

   # Move any other items

   for item, location in action.items():

       if item != 'farmer':

           new_state[item] = location

   return new_state

def is_goal_state(state):

   return state == goal_state

def dfs_solve(state, visited_states):

  

   if is_goal_state(state):

       return [state]

   visited_states.append(state)

  

   for action in actions:

       new_state = apply_action(state, action)
       

       if is_valid(new_state) and new_state not in visited_states:

           

           result = dfs_solve(new_state, visited_states)

           

           if result is not None:

               return [state] + result

   return None

solution = dfs_solve(state, [])

if solution is not None:

   print('Solution found:')

   for step in solution:

       print(step)

else:

   print('No solution found.')

Output:

You might also like