1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public boolean exist(char[][] board, String word) { if(board.length==0) return false; for(int x=0;x<board.length;x++){ for(int y=0;y<board[0].length;y++){ if(search(board,word,x,y,0)) return true; } } return false; } private boolean search(char[][] board, String word, int x, int y, int d){ if(x<0||x>=board.length||y<0||y>=board[0].length) return false; if(word.charAt(d)!=board[x][y]) return false; if(d==word.length()-1) return true; char pre = board[x][y]; board[x][y]=0; boolean flag = search(board,word,x+1,y,d+1)||search(board,word,x-1,y,d+1) ||search(board,word,x,y+1,d+1)||search(board,word,x,y-1,d+1); board[x][y]=pre; return flag; } }
|