Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells is those horizontally or V Ertically neighboring. The same letter cell is used more than once.
For example,
Given board =
[ [' A ', ' B ', ' C ', ' e '], [' s ', ' F ', ' C ', ' s '], [' A ', ' D ', ' e ', ' e ']]
Word = "ABCCED"
, returns true
,
Word = "SEE"
, returns true
,
Word = "ABCB"
, returns false
.
Subscribe to see which companies asked
1 Public classSolution {2 Public BooleanExistChar[] board, String word) {3 if(Word = =NULL|| Word.length () = = 0)return true;4 Boolean[] Visit =New Boolean[Board.length] [Board[0].length];5 Char[] Words =Word.tochararray ();6 for(inti = 0; i < board.length; i++){7 for(intj = 0; J < Board[0].length; J + +){8 if(BFS (BOARD,VISIT,WORDS,0,I,J))return true;9 }Ten } One return false; A } - - Public BooleanBFS (Char[] board,Boolean[] Visit,Char[] Word,intLenintRowintCol) { the if(len = =word.length) { - return true; - } - if(Row < 0 | | row = = Board.length | | Col < 0 | | col = = board[row].length)return false; + if(Board[row][col]! = Word[len])return false; - if(!Visit[row][col]) { +Visit[row][col] =true; A BooleanTMP = BFS (board,visit,word,len+1,row,col+1) | | atBFS (BOARD,VISIT,WORD,LEN+1,ROW,COL-1) | | BFS (board,visit,word,len+1,row+1,col) | | -BFS (board,visit,word,len+1,row-1, col); -Visit[row][col] =false; - returntmp; -}Else return false; - } in}
BFS method code logic and so on two brush time again modified learning under.
Word Search Java Solutions