【leetcode】79. 单词搜索

在这里插入图片描述

搜索回溯

在这里插入图片描述

/**
 * @Auther: Mason
 * @Date: 2020/08/25/20:30
 * @Description:
 */
class Solution {
    
    
    public boolean exist(char[][] board, String word) {
    
    
        // 我的思路是,建立一个map,key是字母,value是list,list中存储坐标值。
        // 这样,当给一个word时,我就知道打头的坐标了。然后遍历word余下的字母。看是不是在前一个字母四周。
        // 当遍历到最后一个字母的时候,就可以返回true了,否则返回false。
        // 总体来说,利用 搜索回溯的方法。
        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;
    }

    // 前一个位置为pos
    // 现在要比对第i个位置。
    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;
    }
}

猜你喜欢

转载自blog.csdn.net/Mason97/article/details/108229021