79. 单词搜索
题目描述
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
贴出代码
class Solution {
public boolean exist(char[][] board, String word) {
int row = board.length;
int column = board[0].length;
char[] str = word.toCharArray();
boolean[][] flag = new boolean[row][column];
for (int i = 0; i < row; i ++){
for (int j = 0;j < column;j ++){
if (backtracking(board,i,j,row,column,flag,str,0)){
return true;
}
}
}
return false;
}
private boolean backtracking(char[][] board, int i,int j,int row,int column,boolean[][] flag, char[] str, int k){
if (i < 0 || j < 0 || i >= row || j >= column || board[i][j] != str[k] || flag[i][j]){
return false;
}
if (k == str.length - 1){
return true;
}
flag[i][j] = true;
if (backtracking(board,i + 1,j,row,column,flag,str,k + 1) ||
backtracking(board,i,j + 1,row,column,flag,str,k + 1) ||
backtracking(board,i - 1, j, row, column, flag,str, k + 1) ||
backtracking(board,i, j - 1,row,column,flag,str, k + 1)){
return true;
}
flag[i][j] = false;
return false;
}
}