larscheng / algo

0 stars 0 forks source link

【Check 62】2024-04-26 - 79. 单词搜索 #165

Open larscheng opened 5 months ago

larscheng commented 5 months ago

79. 单词搜索

larscheng commented 5 months ago

思路

class Solution { public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; boolean[][] used = new boolean[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (check(board, used, i, j, word, 0)) { return true; } } } return false; }

private boolean check(char[][] board, boolean[][] used, int i, int j, String word, int k) {
    if (board[i][j] != word.charAt(k)) {
        return false;
    } else if (k == word.length() - 1) {
        return true;
    }
    boolean result = false;
    used[i][j] = true;
    int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    for (int[] direction : directions) {
        //递归逐个找相邻元素,一直找到不想等的,或者找到最后一个字符结束
        int newI = direction[0] + i;
        int newJ = direction[1] + j;
        if (newI >= 0 && newI < board.length && newJ >= 0 && newJ < board[0].length) {
            if (!used[newI][newJ] && check(board, used, newI, newJ, word, k + 1)) {
                result = true;
                break;
            }
        }
    }
    used[i][j] = false;
    return result;
}

}