比较基础的一道dfs类星题:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix char字符型二维数组 
     * @param word string字符串 
     * @return bool布尔型
     */
    boolean has = false;
    boolean[][] visited;

    public boolean hasPath (char[][] matrix, String word) {
        // write code here
        char[] words = word.toCharArray();
        visited = new boolean[matrix.length][matrix[0].length];

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (!has) {
                    dfs (matrix, i, j, words, 0);
                }
            }
        }

        return has;
    }

    private void dfs (char[][] matrix, int row, int col, char[] words, int index) {

        if (index == words.length) {
            has = true;
        }

        if (!has) {
            if (row >= 0 && row < matrix.length
                && col >= 0 && col < matrix[0].length
                && !visited[row][col] && matrix[row][col] == words[index]) {
                visited[row][col] = true;
                dfs(matrix, row + 1, col, words, index + 1);
                dfs(matrix, row - 1, col, words, index + 1);
                dfs(matrix, row, col + 1, words, index + 1);
                dfs(matrix, row, col - 1, words, index + 1);
                visited[row][col] = false;
            }
        }
    }
}