class Solution {
public boolean exist(char[][] board, String word) {
if (word == null || word.length() == 0) {
return false;
}
boolean[][] visited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (dfs(board, visited, word, 0, i, j)) {
return true;
}
}
}
return false;
}
private boolean dfs(char[][] board, boolean[][] visited, String word, int index, int row, int col) {
if (index == word.length()) {
return true;
}
if (row >= 0 && col >= 0 && row < board.length && col < board[0].length
&& !visited[row][col] && board[row][col] == word.charAt(index)) {
visited[row][col] = true;
if (dfs(board, visited, word, index + 1, row + 1, col) ||
dfs(board, visited, word, index + 1, row - 1, col) ||
dfs(board, visited, word, index + 1, row, col + 1) ||
dfs(board, visited, word, index + 1, row, col - 1)) {
return true;
}
visited[row][col] = false;
}
return false;
}
}
- dfs. Remember to backtrack (change the visited to false after recursive calls)
- Time O(n^2 * 3^word.length())