Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
Solution:
1. Keep a two-dimensional matrix to store the state representing whether the cell has been visited or not.
2. Use DFS to traverse the whole board one by one.
3. Pay attention to the base case of the recursion method.
4. Backtracking. restore the visit matrix every time reaching the end of the DFS method.
public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0)
return false;
int row = board.length;
int col = board[0].length;
boolean[][] visit = new boolean[row][col];
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
if (dfs(board, word, i, j, 0, visit))
return true;
}
return false;
}
public boolean dfs(char[][] board, String word, int i, int j, int wordIndex, boolean[][] visit) {
int row = board.length;
int col = board[0].length;
if (wordIndex >= word.length())
return true;
if (i < 0 || i >= row || j < 0 || j >= col)
return false;
if (word.charAt(wordIndex) != board[i][j])
return false;
if (visit[i][j] == true)
return false;
visit[i][j] = true;
if (dfs(board, word, i - 1, j, wordIndex + 1, visit))
return true;
if (dfs(board, word, i + 1, j, wordIndex + 1, visit))
return true;
if (dfs(board, word, i, j - 1, wordIndex + 1, visit))
return true;
if (dfs(board, word, i, j + 1, wordIndex + 1, visit))
return true;
visit[i][j] = false;
return false;
}
}