Given an m x n board and a word, find if the 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.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Constraints:
- m == board.length
- n = board[i].length
- 1 <= m, n <= 200
- 1 <= word.length <= 103
- board and word consists only of lowercase and uppercase English letters.
class Solution {
/**
ALGORITHM
STEP 1: loop over all the cells in the board
STEP 2: if the cells character is equal to the first letter in word and dfs call is true
-> return true
STEP 3: the word was never found return false
*/
public boolean exist(char[][] board, String word) {
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j] == word.charAt(0) && dfs(board, i, j, word, 0)){
return true;
}
}
}
return true;
}
/*
Input: char[][] board, int row, int col, String word, int index
ALGORITHM
BASE CASE: if index equals the words length
-> return true
BASE CASE: if the row is out of the grid, the col is out of the grid,
or the character at row,col does not equal the character in word at index
-> return false
STEP 1: store the current char
STEP 2: set the current char to ""
STEP 3: call function in all four valid directions
STEP 4: set the current char back
STEP 5: return OR of all four calls
*/
public boolean dfs(char[][] grid, int row, int col, String word, int index){
if(index == word.length()){
return true;
}
if(row < 0 || row >= grid.length || col < 0 || col >= grid[row].length
|| grid[row][col] != word.charAt(index)){
return false;
}
char current = word.charAt(index);
grid[row][col] = ' ';
boolean result =
dfs(grid,row+1,col,word,index+1)
|| dfs(grid,row,col+1,word,index+1)
|| dfs(grid,row-1,col,word,index+1)
|| dfs(grid,row,col-1,word,index+1);
grid[row][col] = current;
return result;
}
}