输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
class Solution {
public boolean exist(char[][] board, String word) {
int iMax = board.length;
int jMax = board[0].length;
boolean flag = false;
boolean[][] visited = new boolean[iMax][jMax];
for (int i = 0; i < iMax; i ++) {
for (int j = 0; j < jMax; j++) {
// 从每个格子开始探索,一旦不符合,跳出从下一格子开始
flag = check(board, i, j, visited, 0, word);
if (flag) {
return true;
}
}
}
return false;
}
private boolean check(char[][] board, int m, int n,boolean[][] visited, int index, String word) {
int iMax = board.length;
int jMax = board[0].length;
// 边界条件检查
if (m >= iMax || m < 0 || n >= jMax || n < 0) {
return false;
}
// 格子是否已访问,如果已访问,则不继续向下执行
if (visited[m][n]) {
return false;
}
// 借助 index 可以知道目前查询到的位置
if (board[m][n] != word.charAt(index)) {
return false;
} else if (index == word.length() - 1) {
return true;
}
boolean flag = false;
// 正在访问的格子要标记为已访问
visited[m][n] = true;
// 想办法尝试向各个方法去探索
flag = check(board, m, n + 1, visited, index + 1, word);
if (flag) {
return true;
}
flag = check(board, m + 1, n,visited, index + 1, word);
if (flag) {
return true;
}
flag = check(board, m, n - 1, visited, index + 1, word);
if (flag) {
return true;
}
flag = check(board, m - 1, n, visited, index + 1, word);
if (flag) {
return true;
}
// 回溯结束,恢复之前的状态
visited[m][n] = false;
return false;
}
}
class Solution {
private int[][] directions = {{0, 1}, {0, -1}, {1, 0}, { -1, 0}};
public boolean exist(char[][] board, String word) {
int iMax = board.length;
int jMax = board[0].length;
boolean flag = false;
boolean[][] visited = new boolean[iMax][jMax];
for (int i = 0; i < iMax; i ++) {
for (int j = 0; j < jMax; j++) {
// 从每个格子开始探索,一旦不符合,跳出从下一格子开始
flag = check(board, i, j, visited, 0, word);
if (flag) {
return true;
}
}
}
return false;
}
private boolean check(char[][] board, int m, int n,boolean[][] visited, int index, String word) {
int iMax = board.length;
int jMax = board[0].length;
// 边界条件检查
if (m >= iMax || m < 0 || n >= jMax || n < 0) {
return false;
}
// 格子是否已访问,如果已访问,则不继续向下执行
if (visited[m][n]) {
return false;
}
// 借助 index 可以知道目前查询到的位置
if (board[m][n] != word.charAt(index)) {
return false;
} else if (index == word.length() - 1) {
return true;
}
// 正在访问的格子要标记为已访问
visited[m][n] = true;
// 想办法尝试向各个方法去探索
for (int[] dir : directions) {
boolean flag = check(board, m + dir[0], n + dir[1], visited, index + 1, word);
if (flag) {
return true;
}
}
// 回溯结束,恢复之前的状态
visited[m][n] = false;
return false;
}
}
x = x + dir[0];
y = y + dir[1];