LeetCode 79 Word Search

·  阅读 62

思路

这题思路很简单。但是我的代码效率并不高,主要有以下两点。

  1. 使用map记录哪些位置的元素已经使用过。一种比较好的做法是,在使用该位置的元素时,将该位置的元素修改为'\0'。此路不通,再改回来。

  2. word传参使用char *更好,避免拷贝。

代码

原始低效率代码如下

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        vector<vector<bool>> alreadyUse(board.size(), vector<bool>(board[0].size(), false));
        
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[0].size(); ++j) {
                if (!alreadyUse[i][j] && board[i][j] == word[0] && search(board, word.substr(1), alreadyUse, i , j))
                    return true;
            }
        }
        
        return false;
    }
    
    bool search(vector<vector<char>> &board, string word, vector<vector<bool>> &alreadyUse, int x, int y) {
        if (word.empty()) return true;
        
        alreadyUse[x][y] = true;
        bool up = false, down = false, left = false, right = false;
        
        if (x > 0 && !alreadyUse[x-1][y] && board[x-1][y] == word[0])
            up = search(board, word.substr(1), alreadyUse, x-1, y);
        if (!up && x < board.size() - 1 && !alreadyUse[x+1][y] && board[x+1][y] == word[0])
            down = search(board, word.substr(1), alreadyUse, x+1, y);
        if (!up && !down && y > 0 && !alreadyUse[x][y-1] && board[x][y-1] == word[0])
            left = search(board, word.substr(1), alreadyUse, x, y-1);
        if (!up && !down && !left && y < board[0].size() - 1 && !alreadyUse[x][y+1] && board[x][y+1] == word[0])
            right = search(board, word.substr(1), alreadyUse, x, y+1);
        
        if (up || down || left || right) return true;
        
        alreadyUse[x][y] = false;
        return false;
        
    }
};
复制代码
分类:
阅读
标签:
收藏成功!
已添加到「」, 点击更改