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.
public class Solution {
public boolean exist(char[][] board, String word) {
if(word.length() == 0) {
return true;
}
int row = board.length;
int col = board[0].length;
boolean[][] visited = new boolean[row][col];
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(helper(board, word, i, j, 0, visited)) {
return true;
}
}
}
return false;
}
private boolean helper(char[][] board, String word, int i, int j, int count, boolean[][] visited) {
if(count == word.length()) {
return true;
}
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return false;
}
if(visited[i][j]) {
return false;
}
if(board[i][j] != word.charAt(count)) {
return false;
}
visited[i][j] = true;
boolean sol = helper(board, word, i + 1, j, count + 1, visited)
|| helper(board, word, i - 1, j, count + 1, visited)
|| helper(board, word, i, j + 1, count + 1, visited)
|| helper(board, word, i, j - 1, count + 1, visited);
visited[i][j] = false;
return sol;
}
}