Besides checking the existence of a traversal, we also want to return such a traversal. Therefore, we realize a class Traversal that exports the following functionalities:
To represent a traversal, we exploit the fact that its length must be equal to
C, i.e., equal to the number of columns of the moor, and that the zones that
belong to the traversal are on successive columns, starting from 0 up to C - 1.
Hence, we can use an array of C integer elements in which the value of the
generic element of index c is equal to the index r of the row of zone
< r, c > belonging to the traversal. For example, the traversal shown in
moor 2 above is represented by the array {
1,2,3,3,3,2}
.
In the following implementation, we have chosen to add to the methods searchPath() and traverseMoor() an additional parameter, of type array of integers, that represents a path, and have the methods do side-effect by updating the path in an appropriate way. The implementation of the method toString() is left as an exercise.
public class Traversal { private int[] traversal; private Moor moor; private boolean found; public Traversal(Moor m) { moor = m; traversal = new int[moor.getNumColumns()]; found = traverseMoor(moor, traversal); } public Moor moor() { return moor; } public boolean existsTraversal() { return found; } public int length() { if (found) return traversal.length; else throw new RuntimeException("Traversal: traversal does not exist"); } public int step(int i) { if (found) return traversal[i]; else throw new RuntimeException("Traversal: traversal does not exist"); } public String toString() { ... } // auxiliary methods private static boolean traverseMoor(Moor m, int[] path) { for (int row = 0; row < m.getNumRows(); row++) if (searchTraversal(m, row, 0, path)) return true; return false; } private static boolean searchTraversal(Moor m, int r, int c, int[] path) { if (!m.land(r,c)) return false; else { path[c] = r; if (c == m.getNumColumns()-1) return true; else return searchTraversal(m, r-1, c+1, path) || searchTraversal(m, r, c+1, path) || searchTraversal(m, r+1, c+1, path); } } }