矩阵中的路径

描述:矩阵中的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。

eg:下面3 x 4的矩阵中包含一条字符串”bcced”的路径,但矩阵中不包含”abcd”的路径。
a b c e
s f c s
a d e e

public class MatrixPath {
    private char[] matrix;
    private int rows;
    private int cols;

    public MatrixPath(String m, int rows, int cols) {
        if (m == null)
            throw new NullPointerException();
        matrix = m.toCharArray();
        this.rows = rows;
        this.cols = cols;
        if (rows * cols != matrix.length || rows < 1 || cols < 1)
            throw new IllegalArgumentException();
    }

    public boolean hasPath(String str) {
        boolean[] visited = new boolean[rows * cols];
        int pathLength = 0;
        char[] sub = str.toCharArray();

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (hasPathCore(row, col, sub, pathLength, visited))
                    return true;
            }
        }
        return false;
    }

    private boolean hasPathCore(int row, int col, char[] sub, 
            int pathLength, boolean[] visited) {
        if (pathLength >= sub.length)
            return true;

        boolean hasPath = false;
        if (row >= 0 && row < rows && col >= 0 &&
                col < cols &&
                matrix[row * cols + col] == sub[pathLength] &&
                !visited[row * cols + col]) {
            pathLength++;
            visited[row * cols + col] = true;
            hasPath = hasPathCore(row, col - 1, sub, pathLength, visited) ||
                    hasPathCore(row, col + 1, sub, pathLength, visited) ||
                    hasPathCore(row + 1, col, sub, pathLength, visited) ||
                    hasPathCore(row - 1, col, sub, pathLength, visited) ;
            if (!hasPath) {
                pathLength--;
                visited[row * cols + col] = false;
            }
        }
        return hasPath;
    }

    public static void main(String[] args) {
        String test = "abcesfcsadee";
        MatrixPath matrix = new MatrixPath(test, 3, 4);
        System.out.println(matrix.hasPath("bcced"));
        System.out.println(matrix.hasPath("abcd"));
        System.out.println(matrix.hasPath("escfd"));
        System.out.println(matrix.hasPath("bccedfsa"));
    }
}