79. Word Search
Given a two-dimensional grid and a word, to find out whether the word exists in the grid.
Words must, by the letters in adjacent cells constituting alphabetically, where "adjacent" cells that are adjacent horizontally or vertically adjacent cells. Letters within the same cell is not allowed to be reused.
Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = "ABCCED", returns true.
Given word = "SEE", returns true.
Given word = "ABCB", returns false.
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 (search(board, word, i, j, 0)) {
return true;
}
}
}
return false;
}
boolean search(char[][] board, String word, int i, int j, int k) {
if (k >= word.length()) return true;
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(k)) return false;
board[i][j] += 256;
boolean result = search(board, word, i - 1, j, k + 1) || search(board, word, i + 1, j, k + 1)
|| search(board, word, i, j - 1, k + 1) || search(board, word, i, j + 1, k + 1);
board[i][j] -= 256;
return result;
}
}