next up previous
Next: Moor: construction of the Up: Unit 11 Previous: Moor: representation of a

Moor: solution of the traversal problem

The solution requires to find a sequence of zones of the moor such that the first zone is in column 1 and the last zone is in column C. Each position in the sequence must be adjacent to the following one. For example, if the first position is < 3, 1 >, the second one could be < 4, 2 >, but not < 3, 3 >. Since at each step we have to move to the right, the sequence will have exactly C steps.

To explore the moor, we use a recursive method. This is the most intuitive choice, since the search process is inherently recursive. The algorithm can be summarized as follows: in the first step we look for a land zone in the first column. If there is one, we start from that zone. In the generic recursive step we are in a zone < r, c >. If the zone is a land zone, we can go on and we continue the search recursively from the adjacent positions, namely < r - 1, c + 1 >, < r, c + 1 >, and < r + 1, c + 1 >. Instead, if the zone is a water zone, we cannot go on and the search from that zone terminates. The overall search terminates with success when we arrive on a zone on the last column (i.e., c is equal to C - 1) and such a zone is of land.

The generic search step can be implemented through the following recursive method searchPath(), that takes as parameters a moor and the coordinates < r, c > of the zone from where to start searching the path through the moor.

private static boolean searchPath(Moor m, int r, int c) {
  if (the coordinates <r,c> of m are not valid ||
      in m <r,c> is a water zone)
    return false;
  else if (<r,c> is on the right border of m)
    return true;
    return searchPath(m, r-1, c+1) ||
           searchPath(m, r  , c+1) ||
           searchPath(m, r+1, c+1);

The method searchPath() checks only if there is a path from a generic position < r, c > to the last column. Since a path could start from an arbitrary position on the first column, we have to repeatedly call this method on the positions < r, 0 > of the first column, until we have found a traversal or we have searched without success by starting in the first column of all rows up to the last one. This is done by a method traverseMoor().

next up previous
Next: Moor: construction of the Up: Unit 11 Previous: Moor: representation of a