public static int[][] direction = new int[][]{{0,-1},{0,1},{1,0},{-1,0}}; public boolean exist(char[][] board, String word) { //dfs int m = board.length; int n = board[0].length; boolean[][] flag = new boolean[m][n]; for(int i = 0 ; i < m ; i++) { for(int j = 0 ; j < n ; j++) { if(dfs(board,i,j,flag,word,0)) { return true; } } } return false; } public boolean dfs(char[][] board,int i , int j ,boolean[][] flag , String word , int index) { if(index == word.length()) { return true; } if( i >= board.length || i < 0 || j >= board[0].length || j < 0 || flag[i][j] || word.charAt(index) != board[i][j]) { return false; } flag[i][j] = true; boolean cur = dfs(board,i + direction[0][0],j+direction[0][1],flag,word,index+1) || dfs(board,i + direction[1][0],j+direction[1][1],flag,word,index+1) || dfs(board,i + direction[2][0],j+direction[2][1],flag,word,index+1) || dfs(board,i + direction[3][0],j+direction[3][1],flag,word,index+1); flag[i][j] = false; return cur; }