搜索回溯
class Solution {
public boolean exist(char[][] board, String word) {
if (word == null || word.length() == 0) return false;
char first = word.charAt(0);
int[][] move = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
boolean[][] used = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == first) {
int[] pos = new int[]{i, j};
used[pos[0]][pos[1]] = true;
if (dfs(pos, board, 1, word.length(), move, word, used)) return true;
used[i][j] = false;
}
}
}
return false;
}
private boolean dfs(int[] pos, char[][] board, int i, int length, int[][] move, String word, boolean[][] used) {
if (i == length) return true;
int ii, jj;
for (int[] m : move) {
ii = pos[0] + m[0];
jj = pos[1] + m[1];
if (ii < 0 || ii >= board.length || jj < 0 || jj >= board[0].length) continue;
if (used[ii][jj]) continue;
if (board[ii][jj] != word.charAt(i)) continue;
used[ii][jj] = true;
if (dfs(new int[]{ii, jj}, board, i + 1, length, move, word, used)) return true;
used[ii][jj] = false;
}
return false;
}
}