Q: 1 -> WORD SEARCH .
Code :
javaCopy codeclass Solution {
public boolean exist(char[][] board, String word) {
int row = board.length;
int cols = board[0].length;
for(int i = 0; i < row; i++){
for(int j = 0; j < cols; j++){
if(board[i][j] == word.charAt(0) && fn(board, word, i, j, 0, new boolean[row][cols])){
return true;
}
}
}
return false;
}
static boolean fn(char[][] grid, String word, int r, int c, int idx, boolean[][] visited) {
// base case.
if(idx == word.length()){
return true;
}
if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || word.charAt(idx) != grid[r][c] || visited[r][c]){
return false;
}
// rec case.
visited[r][c] = true;
if(
fn(grid, word, r + 1, c, idx + 1, visited) ||
fn(grid, word, r - 1, c, idx + 1, visited) ||
fn(grid, word, r, c + 1, idx + 1, visited) ||
fn(grid, word, r, c - 1, idx + 1, visited)
){
visited[r][c] = false;
return true;
}
// back-track visited.
visited[r][c] = false;
return false;
}
}