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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class Solution { boolean flag=false; public boolean exist(char[][] board, String word) { boolean[][] skipped=new boolean[board.length][board[0].length]; for(int i=0;i<board.length;i++){ for(int j=0;j<board[i].length;j++){ if(board[i][j]==word.charAt(0)){ skipped[i][j]=true; func(board,skipped,word,0,i,j); skipped[i][j]=false; } } if(flag)break; } return flag; }
void func(char[][] board,boolean[][]skipped,String word,int index,int r,int c){ if(index==word.length()-1){ flag=true; return; }
if(r>0&&board[r-1][c]==word.charAt(index+1)&&!skipped[r-1][c]){ skipped[r-1][c]=true;
func(board,skipped,word,index+1,r-1,c);
skipped[r-1][c]=false; } if(r<board.length-1&&board[r+1][c]==word.charAt(index+1)&&!skipped[r+1][c]){ skipped[r+1][c]=true;
func(board,skipped,word,index+1,r+1,c);
skipped[r+1][c]=false; } if(c>0&&board[r][c-1]==word.charAt(index+1)&&!skipped[r][c-1]){ skipped[r][c-1]=true;
func(board,skipped,word,index+1,r,c-1);
skipped[r][c-1]=false; } if(c<board[r].length-1&&board[r][c+1]==word.charAt(index+1)&&!skipped[r][c+1]){ skipped[r][c+1]=true;
func(board,skipped,word,index+1,r,c+1);
skipped[r][c+1]=false; } } }
|