212 Word Search II [Leetcode]

44 篇文章 0 订阅
4 篇文章 0 订阅

题目内容:

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,
Given words = [“oath”,”pea”,”eat”,”rain”] and board =

[
[‘o’,’a’,’a’,’n’],
[‘e’,’t’,’a’,’e’],
[‘i’,’h’,’k’,’r’],
[‘i’,’f’,’l’,’v’]
]

Return [“eat”,”oath”].

解题思路:
使用words中的单词构造一棵Trie树以方便快速查找,然后和Word Search类似,使用回溯实现在字母方阵中的查找。
1. 为了防止重复访问,因为字母的范围是小写字母,我们将board中访问过的字母标记为’*’,来防止重复访问。
2. 为了在存储结果时能够快速获得字符串,在构造Trie树时,若该节点为叶子节点,将该字符串存在叶节点上。
3. 为了防止某个字符多次出现,使用set或者unordered_set存储出现过的字符。

未优化代码:

struct TrieNode {
    string leaf;
    vector<TrieNode *> subNodes;

    TrieNode() {
        subNodes = vector<TrieNode *>(26, NULL);
    }

    void setLeaf(string str) {
        leaf = str;
    }

    bool isLeaf() {
        return !leaf.empty();
    }
};

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        set<string> sresult;
        TrieNode *root = constructTrie(words);

        for(int i = 0; i < board.size(); ++i) {
            for(int j = 0; j < board[0].size(); ++j) {
                char temp = board[i][j];
                board[i][j] = '*';
                backtracking(root->subNodes[temp - 'a'], board, sresult, i, j);
                board[i][j] = temp;
            }
        }

        vector<string> result(sresult.begin(), sresult.end());
        return result;
    }

    void backtracking(TrieNode *node, vector<vector<char>> &board, set<string> &result, int r, int c) {
        if(node == NULL)
            return;

        if(node->isLeaf()) {
            result.insert(node->leaf);
        }

        char temp;
        if(r > 0 && board[r-1][c] != '*') {
            temp = board[r-1][c];
            board[r-1][c] = '*';
            backtracking(node->subNodes[temp - 'a'], board, result, r-1, c);
            board[r-1][c] = temp;
        }
        if(r < board.size() - 1 && board[r+1][c] != '*') {
            temp = board[r+1][c];
            board[r+1][c] = '*';
            backtracking(node->subNodes[temp - 'a'], board, result, r+1, c);
            board[r+1][c] = temp;
        }
        if(c > 0 && board[r][c-1] != '*') {
            temp = board[r][c-1];
            board[r][c-1] = '*';
            backtracking(node->subNodes[temp - 'a'], board, result, r, c-1);
            board[r][c-1] = temp;
        }
        if(c < board[0].size() - 1 && board[r][c+1] != '*') {
            temp = board[r][c+1];
            board[r][c+1] = '*';
            backtracking(node->subNodes[temp - 'a'], board, result, r, c+1);
            board[r][c+1] = temp;
        }
    }

    TrieNode *constructTrie(vector<string> &words) {
        TrieNode *p, *root = new TrieNode();

        for(int i = 0; i < words.size(); ++i) {
            p = root;
            for(int j = 0; j < words[i].size(); ++j) {
                if(p->subNodes[words[i][j] - 'a'] == NULL) {
                    p->subNodes[words[i][j] - 'a'] = new TrieNode();
                }
                p = p->subNodes[words[i][j] - 'a'];
            }
            p->setLeaf(words[i]);
        }

        return root;
    }
};

这里使用set和unordered_set时间基本没有差别。由于上面代码存在一定的冗余且功能分工不明确,进行了一些优化。优化后时间稍微慢了点,但也相差不多。慢了的原因主要是将对下标越界的判断放到了递归函数的头部,使得函数调用的次数变多了。

改进后代码:

struct TrieNode {
    string leaf;
    vector<TrieNode *> subNodes;

    TrieNode() {
        subNodes = vector<TrieNode *>(26, NULL);
    }

    void setLeaf(string str) {
        leaf = str;
    }

    bool isLeaf() {
        return !leaf.empty();
    }
};

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        set<string> sresult;
        TrieNode *root = constructTrie(words);

        for(int i = 0; i < board.size(); ++i) {
            for(int j = 0; j < board[0].size(); ++j) {
                backtracking(root, board, sresult, i, j);
            }
        }

        vector<string> result(sresult.begin(), sresult.end());
        return result;
    }

    void backtracking(TrieNode *node, vector<vector<char>> &board, set<string> &result, int r, int c) {
        if(node == NULL)
            return;

        if(node->isLeaf()) {
            result.insert(node->leaf);
        }

        if(r < 0 || r == board.size() || c < 0 || c == board[0].size() || board[r][c] == '*')
            return;

        char temp = board[r][c];
        board[r][c] = '*';

        backtracking(node->subNodes[temp - 'a'], board, result, r-1, c);
        backtracking(node->subNodes[temp - 'a'], board, result, r+1, c);
        backtracking(node->subNodes[temp - 'a'], board, result, r, c-1);
        backtracking(node->subNodes[temp - 'a'], board, result, r, c+1);

        board[r][c] = temp;
    }

    TrieNode *constructTrie(vector<string> &words) {
        TrieNode *p, *root = new TrieNode();

        for(int i = 0; i < words.size(); ++i) {
            p = root;
            for(int j = 0; j < words[i].size(); ++j) {
                if(p->subNodes[words[i][j] - 'a'] == NULL) {
                    p->subNodes[words[i][j] - 'a'] = new TrieNode();
                }
                p = p->subNodes[words[i][j] - 'a'];
            }
            p->setLeaf(words[i]);
        }

        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值