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.
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
.
public boolean exist(char[][] board, String word) {
char[] chars = word.toCharArray();
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[i].length; j++)
if (exist(board, i, j, chars, 0)) return true;
return false;
}
public boolean exist(char[][] board, int i, int j, char[] word, int start) {
if (start == word.length) return true;
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false;
if (board[i][j] == word[start++]) {
char flag = board[i][j];
board[i][j] = '#';
boolean result = exist(board, i - 1, j, word, start) || exist(board, i + 1, j, word, start) ||
exist(board, i, j - 1, word, start) || exist(board, i, j + 1, word, start);
board[i][j] = flag;
return result;
}
return false;
}