79 Word Search
79. Word Search
1. Question
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]2. Implementation
3. Time & Space Complexity
Last updated
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]Last updated
class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || word == null || word.length() == 0) {
return false;
}
int m = board.length, n = board[0].length;
boolean[][] visited = new boolean[m][n];
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (searchWord(0, i, j, word, directions, visited, board)) {
return true;
}
}
}
return false;
}
public boolean searchWord(int index, int row, int col, String word, int[][] directions, boolean[][] visited, char[][] board) {
if (index == word.length()) {
return true;
}
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != word.charAt(index) || visited[row][col]) {
return false;
}
visited[row][col] = true;
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (searchWord(index + 1, nextRow, nextCol, word, directions, visited, board)) {
return true;
}
}
visited[row][col] = false;
return false;
}
}