79. Word Search
题目描述
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,
Givenboard=
解题方法
public boolean exist(char[][] board, String word){
if(board == null || board.length == 0){
return false;
}
if(word.length() == 0){ return false;}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] == word.charAt(0)){
boolean rst = helper(board, word, 0, i, j);
if(rst){ return true;}
}
}
}
return false;
}
int[][] directions = new int[][]{{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
private boolean helper(char[][] board, String word, int index, int row, int col){
boolean flag = false;
if(index == word.length()){return true;}
if(row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != word.charAt(index)){
return false;
}
for(int i = 0; i < directions.length; i++){
board[row][col] = '#';
flag |= helper(board, word, index + 1, row + directions[i][0], col + directions[i][1]);
if(flag == true){return true;}
board[row][col] = word.charAt(index);
}
return flag;
}