#79. Word Search 题目链接
public class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
// 遍历每一个点作为起点
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (exist(board, words, i, j, 0)) {
return true;
}
}
}
return false;
}
public boolean exist(char[][] borad, char[] words, int x, int y, int i) {
if (i == words.length) {
return true;
}
if (x < 0 || y < 0 || x >= borad.length || y >= borad[0].length) {
return false;
}
if (borad[x][y] != words[i]) {
return false;
}
// 设置已访问
borad[x][y] ^= 255;
i++;
// 递归查找邻接点
boolean flag = exist(borad, words, x+1, y, i) || exist(borad, words, x-1, y, i)
|| exist(borad, words, x, y+1, i) || exist(borad, words, x, y-1, i);
// 恢复原值
borad[x][y] ^= 255;
return flag;
}
}