79. Word Search (Backtracking)
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.class Solution {
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (helper(board, word, i, j, 0)) return true;
}
}
return false;
}
private boolean helper(char[][] board, String word, int i, int j, int index) {
if (index >= word.length()) return true;
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false;
if (word.charAt(index) != board[i][j]) return false;
index++;
char c = board[i][j];
board[i][j] = '*';
boolean res = helper(board, word, i + 1, j, index)
|| helper(board, word, i - 1, j, index)
|| helper(board, word, i, j + 1, index)
|| helper(board, word, i, j - 1, index);
board[i][j] = c; // restore this cell
return res;
}
}Last updated