// 2017.4.26
// 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.
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (recursionBoard(board, i, j, word, 0)) {
return true;
}
}
}
return false;
}
boolean recursionBoard(char[][] board,int x,int y,String word,int start) {
if (start >= word.length()) {
return true;
}
if (x < 0 || x >= board.length || y < 0 || y >= board[x].length) {
return false;
}
if (word.charAt(start++) == board[x][y]) {
char c = board[x][y];
board[x][y] = '*';
boolean res = recursionBoard(board, x - 1,y,word,start) ||
recursionBoard(board, x + 1,y,word,start) ||
recursionBoard(board, x,y - 1,word,start) ||
recursionBoard(board, x,y + 1,word,start);
board[x][y] = c;
return res;
}
return false;
}
网友评论