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 =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word = "ABCB"
, -> returns false
.
Solution Backtracking
10ms 87%
public class Solution {
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0)
return false;
if(word.length() == 0)
return true;
char [] w = word.toCharArray();
for(int y = 0; y < board.length; y++){
for(int x = 0; x < board[y].length; x++){
if(existHelper(board, y, x, w, 0)){
return true;
}
}
}
return false;
}
public boolean existHelper(char [][] board, int y, int x, char[] word, int po){
if(po == word.length){
return true;
}
if(x < 0 || y < 0 || y == board.length || x == board[y].length){
return false;
}
if(word[po] != board[y][x]){
return false;
}
board[y][x] = '*';
boolean exist = existHelper(board, y - 1, x, word, po + 1) || existHelper(board, y + 1, x, word, po + 1) ||
existHelper(board, y, x - 1, word, po + 1) || existHelper(board, y, x + 1, word, po + 1);
board[y][x] = word[po];
return exist;
}
}