ref

class Solution {
    //深度优先+回溯,
    
    int[][] directions = {{0,1},{0,-1},{1,0},{-1,0}};  
    public boolean exist(char[][] board, String word) {
        int row = board.length;
        int col = board[0].length;
        boolean[][] visited = new boolean[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                    if (dfs(i,j,board,word,0,visited)) {
                        return true;
                    }
                } 
            }
            return false;
    }
   
    public boolean dfs(int row, int col, char[][] board, String word, int index, boolean[][] visited) {
        if (index == word.length()) {
            return true;
        }
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || word.charAt(index) != board[row][col] || visited[row][col] == true) {
            return false;
        }
        visited[row][col] = true; // 对当前的路径进行标记,避免重复访问
        for (int[] dir : directions) {
            int curRow = row + dir[0];
            int curRol = col + dir[1];
            if (dfs(curRow, curRol, board, word, index + 1, visited)) {
                return true;
            }
        }
        visited[row][col] = false; // 回溯,使得其他路径可以访问当前路径的元素
        return false;

    }
}

八皇后写法

class Solution {
    public boolean exist(char[][] board, String word) {
        int l = board.length;
        int w = board[0].length;
        boolean[][] visited = new boolean[l][w];
        for(int i=0;i<l;i++){
            for(int j=0;j<w;j++){
                if(pd(board,visited,word,0,i,j)) return true;
            }
        }
        return false;
    }

    public boolean pd(char[][] board,boolean visited[][],String word,int index,int i,int j){
        if(index == word.length()) return true;
        if(i<0||i>=board.length||j<0||j>=board[0].length||visited[i][j]||board[i][j] != word.charAt(index)) return false;
        visited[i][j] = true;
        boolean res = pd(board,visited,word,index+1,i+1,j)|pd(board,visited,word,index+1,i,j+1)|pd(board,visited,word,index+1,i-1,j)|pd(board,visited,word,index+1,i,j-1);
        visited[i][j] = false;
        return res;
    }
}