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 are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.
Copy public class Solution {
public boolean exist ( char [][] board , String word) {
for ( int i = 0 ; i < board . length ; i ++ ) {
for ( int j = 0 ; j < board[ 0 ] . length ; j ++ ) {
if ( dfs(board , 0 , i , j , word) ) {
return true ;
}
}
}
return false ;
}
public boolean dfs ( char [][] board , int start , int x , int y , String word) {
if (start == word . length ()) {
return true ;
}
if (x < 0 || x >= board . length || y < 0 || y >= board[ 0 ] . length || board[x][y] != word . charAt (start))
return false ;
char temp = board[x][y];
board[x][y] = '#' ;
boolean result = dfs(board , start + 1 , x - 1 , y , word) || dfs(board , start + 1 , x + 1 , y , word) || dfs(board , start + 1 , x , y - 1 , word) || dfs(board , start + 1 , x , y + 1 , word) ;
board[x][y] = temp;
return result;
}
}