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.
Example
Given board =
[ "ABCE", "SFCS", "ADEE" ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
public class Solution {
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
public boolean exist(char[][] board, String word) {
if(word == null || word.length() == 0) return true;
if(board.length == 0 || board[0].length == 0) return false;
boolean[][] visit = 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(helper(board, visit, i, j, 0, word)) return true;
}
}
return false;
}
boolean helper(char[][] board, boolean[][] visit, int row, int col, int index, String str) {
if(index >= str.length()) {
return true;
}
if(row < 0 || col < 0 || row >= board.length || col >= board[0].length) {
return false;
}
if(!visit[row][col] && str.charAt(index) == board[row][col]) {
visit[row][col] = true;//<-
boolean res = helper(board, visit, row + 1, col, index + 1, str) ||
helper(board, visit, row - 1, col, index + 1, str) ||
helper(board, visit, row, col + 1, index + 1, str) ||
helper(board, visit, row, col - 1, index + 1, str);
visit[row][col] = false;//<-
return res;
}
return false;
}
}