/**
* 79. Word Search
* 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
*/
See solution to the problem on github here: https://github.com/zcoderz/leetcode/blob/main/src/main/java/backtracking/WordSearch.java
This algorithm is fairly straightforward. You are traversing the two-dimensional array for a possible match. If match doesn’t occur, you back track and try a different direction. These types of questions are common and hence included here.
Here is the code:
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 (traverse(i, j, board, word, 0)) {
return true;
}
}
}
return false;
}
public boolean traverse(int row, int col, char [][] board, String word, int wordIndex) {
if (wordIndex >= word.length()) {
return true;
}
char ch = word.charAt(wordIndex);
if (row < 0 || col <0 || col == board[0].length || row == board.length ||
board[row][col] != ch) {
return false;
}
board[row][col]='#';
for (int i =0 ; i < 4; i++) {
int nCol = col + colMoves[i];
int nRow = row + rowMoves[i];
if (traverse(nRow, nCol, board, word, wordIndex + 1)) {
board[row][col] = ch;
return true;
}
}
board[row][col] = ch;
return false;
}