Week 11: Exercises

1. Connected Maze

Write a program that reads a rectangular maze from standard input in the following format, where '#' represents a wall:

########
# #  # #
# # #  #
#   # ##
##     #
########

The maze will be surrounded by walls.

The program should print True if the maze is connected, i.e. every two empty squares in the maze are connected by some path. Otherwise print False.

2. Showing the Path

Write a function that takes a 2-dimensional array of booleans representing a maze. There will be no wall in the upper-left or lower-right corner.

The procedure should print out the maze, indicating the shortest path from the upper-left corner to the lower-right corner. For example, the output might look like this:

..######
#.#    #
#.# #  #
#...#  #
## ....#
######..

If no such path exists, print the maze without any path.

3. Limping Knight

Consider a limping knight on a chessboard. On odd moves (including the first move), it moves like a pawn, i.e. one square forward (or stays in place if it is at the top of the board). On even moves, it moves like a normal knight in chess. Write a function limping_dist(start, end) that returns the smallest number of moves that the knight must make to go from a given starting square to a given ending square. Assume that squares are pairs of coordinates, i.e. (1, 1) is the upper-left corner of the chessboard and (8, 8) is the lower-right corner.

4. State Space Solver

Write a function solve(start, goal, f) that can search any state space. solve() should take three arguments: a start state, a goal state, and a function f that computes the neighbors of any state. solve() should find the shortest possible path from the start state to the goal state, and should print out the sequence of states along this path, with one state per line. If no solution is possible, it should print 'no path'.

5. Water Jugs

We have three jugs with capacity 8, 5, and 3 liters. Initially the first jug is full of water, and the others are empty.

We can pour water between the jugs, but they have no markings of any sort, so we can pour between two jars only until one of them becomes full or empty.

What sequence of moves can we make so that the jugs will hold 4, 4, and 0 liters of water, respectively?

Write a program that can find the shortest possible sequence.

6. Missionaries and Cannibals

Three missionaries and three cannibals are on the west bank of a river. They have a canoe that can hold two people, and they all must cross to the east bank of the river. There may never be more cannibals than missionaries on either side of the river, or the cannibals will eat the missionaries. Further, the canoe must have at least one person on board to cross the river. Write a program to find and print a sequence of crossings that will take the party safely across.