力扣-79-单词搜索

刚做了前缀树,前缀树可以用来在一维空间上做单词搜索,而这里是二维,本质上是查找一个路径,像是DFS

好吧其实是回溯

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        int n = board[0].size();

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (check(board,word,i,j,0)) return true;

        return false;
    }

    bool check(vector<vector<char>>& board, string word, int i,int j,int index) {
        if (board[i][j] == word[index]) {
            if (index == word.size() - 1) return true;
            // 这里只要是一个原数组不会出现的字符就行
            board[i][j] = '#';
            if (i - 1 >= 0) 
                if (check(board, word, i-1, j, index+1)) return true;
            
            if (i + 1 < board.size()) 
                if (check(board, word, i + 1, j, index+1)) return true;
            
            if (j - 1 >= 0) 
                if (check(board, word, i, j-1, index+1)) return true;
            
            if (j + 1 < board[0].size()) 
                if (check(board, word, i, j+1, index+1)) return true;
            
            board[i][j] = word[index];
        }
        return false;
    }
};

第一版AC代码,然后就是考虑优化和剪枝
…好像没啥好改的,每一步都很清晰

posted @ 2022-12-13 11:22  YaosGHC  阅读(29)  评论(0)    收藏  举报