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 (board == null || board.length == 0) return false;
if (word == null || word.length() == 0) return true;
boolean[][] visited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (valid(board, word, visited, i, j, 1)) return true;
}
}
return false;
}
public boolean valid(char[][] board, String word, boolean[][] visited, int i, int j, int k) {
if (board[i][j] != word.charAt(k - 1)) return false;
if (k == word.length()) return true;
visited[i][j] = true;
//up
if (i - 1 >= 0 && !visited[i - 1][j] && valid(board, word, visited, i - 1, j, k + 1)) {
return true;
}
//down
if (i + 1 <= board.length - 1 && !visited[i + 1][j] && valid(board, word, visited, i + 1, j, k + 1)) {
return true;
}
//left
if (j - 1 >= 0 && !visited[i][j - 1] && valid(board, word, visited, i, j - 1, k+1)) {
return true;
}
//right
if (j + 1 <= board[0].length - 1 && !visited[i][j + 1] && valid(board, word, visited, i, j + 1, k+1)) {
return true;
}
visited[i][j] = false;
return false;
}
}