Introduction to Algorithms, 2021-2
Week 13: Exercises

1. Connected Graph

Write a function that takes an undirected graph in adjacency matrix representation. The function should return True if the graph is connected, i.e. there is some path between every pair of vertices.

2. Reachable Vertices

Write a function that takes a directed graph in adjacency list representation and two vertex ids v and w. The function should return True if v and w are mutually reachable, i.e. there is some path from v to w and also from w to v.

3. Shortest Path

Write a function that takes a graph and two vertex ids v and w, and returns a list of vertex ids containing a path from v to w that is as short as possible.

4. On the Path

Write a function that takes a graph that is a tree, i.e. a connected, undirected, acyclic graph. The function should also take three vertex ids v, w, and x. The function should return true if w is between v and x, i.e. on the (unique) path that leads from v to x.

5. 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.

6. 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.

7. Limping Knight

Consider a limping knight on a chessboard. On odd moves, 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.