Word Search
Word Search
Word Search
Medium
Given an m x n grid of characters board and a string word , return true if word exists in the
grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells
are horizontally or vertically neighboring. The same letter cell may not be used more than
once.
class Solution {
public boolean exist(char[][] board, String word) {
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 (backtrack(board, word, 0, i, j, visited)) return true;
}
}
return false;
}
private boolean backtrack(char[][] board, String word, int idx, int i, int j,
boolean[][] visited) {
if (idx == word.length()) return true;
visited[i][j] = true;
boolean found = backtrack(board, word, idx + 1, i + 1, j, visited) ||
backtrack(board, word, idx + 1, i, j + 1, visited) ||
backtrack(board, word, idx + 1, i - 1, j, visited) ||
backtrack(board, word, idx + 1, i, j - 1, visited);
visited[i][j] = false;
return found;
}
}
Time Complexity : O(M * N * 4^L) | Space Complexity : O(M * N)
Runtime 141ms | Beats 68.05%