[leetcode] 79. 单词搜索
这个题跟前两个题思路类似,递归搜即可
先找到首节点,然后4个方向去搜。
状态函数:dfs(int i, int j, int k, char[][] board, String word, int m, int n, boolean[][] f)
i,j表示当然已经搜到了节点(i,j)
k表示下一个将要找的字母是word[k]
class Solution {
static int[][] d = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public boolean exist(char[][] board, String word) {
int m = board.length;
if (m == 0) return false;
int n = board[0].length;
if (n == 0) return false;
if (word.equals("")) return true;
boolean[][] f = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (word.charAt(0) == board[i][j]) {
f[i][j] = true;
boolean flag = dfs(i, j, 1, board, word, m, n, f);
if (flag) return true;
f[i][j] = false;
}
}
}
return false;
}
private boolean dfs(int i, int j, int k, char[][] board, String word, int m, int n, boolean[][] f) {
if (k == word.length()) {
return true;
}
for (int l = 0; l < 4; l++) {
if (i + d[l][0] < m && j + d[l][1] < n && i + d[l][0] >= 0 && j + d[l][1] >= 0 && board[i + d[l][0]][j + d[l][1]] == word.charAt(k) && !f[i + d[l][0]][j + d[l][1]]) {
f[i + d[l][0]][j + d[l][1]] = true;
boolean flag = dfs(i + d[l][0], j + d[l][1], k + 1, board, word, m, n, f);
if (flag) return true;
f[i + d[l][0]][j + d[l][1]] = false;
}
}
return false;
}
}