class Solution {
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0 || board[0].length == 0 || word == null || word.length() == 0) return false;
int rows = board.length;
int cols = board[0].length;
for(int i=0; i < rows; i++) {
for(int j = 0; j < cols; j++){
if(search(board, word, i, j, 0))
return true;
}
}
return false;
}
private boolean search(char[][] board, String word, int i, int j, int pos) {
if(pos == word.length()) return true;
if(board[i][j] != word.charAt(pos))
return false;
int rows = board.length;
int cols = board[0].length;
board[i][j] = '.';
if(pos == word.length()-1) return true;
if (( i+1 < rows && board[i+1][j] != '.' && search(board, word, i + 1, j, pos+1) ) ||
( i-1 >= 0 && board[i-1][j] != '.' && search(board, word, i - 1, j, pos+1) ) ||
( j+1 < cols && board[i][j+1] != '.' && search(board, word, i, j + 1, pos+1) ) ||
( j-1 >=0 && board[i][j-1] != '.' && search(board, word, i, j - 1, pos+1) ) ) {
return true;
}
board[i][j] = word.charAt(pos);
return false;
}
}