LeetCode 212-Word Search II

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"].

Note:

You may assume that all inputs are consist of lowercase letters a-z.

分析

参照Word Search,我先尝试使用类似的方法。由于查询单词需要从board的某个坐标点(i, j)出发,如果查询每个单词都得遍历一遍board显然效率太低。因此我使用一个哈希表纪录了board中不同字母起点的坐标,比如例子中‘a’的起点有[[0,1],[0,2],[1,2]]。由此,在查询过程中可以直接从哈希表中取起点,无需遍历board。

但最后这个算法Time Limit Exceeded,原因如下:对于相同前缀的words中的若干个单词,我们机械地查找了多次,实际上只需要查询一次即可。如["aaaaaa", "aaaaab", "aaaaac"],它们都具有相同的前缀“aaaaa”。改进方法后面再分析,先给出这个TLE的算法:

TLE代码

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> answer;
        int row = board.size();
        int col = board[0].size();
        vector<vector<pair<int, int>>> store(26);

        for (int i = 0; i != row; ++i) {
            for (int j = 0; j != col; ++j) {
                int index = find(board[i][j]);
                store[index].push_back(make_pair(i, j));
            }
        }

        for (string word : words) {
            if (!word.size()) {
                answer.push_back("");
                break;
            }
            int index = find(word[0]);
            for (auto pair : store[index]) {
                if (search(board, pair.first, pair.second, word, 0)) {
                    answer.push_back(word);
                }
            }
        }
        return answer;
    }

    int find(char letter) { return static_cast<int> (letter - 'a'); }

    bool search(vector<vector<char>>& board, int i, int j, string word, int k) {
        if (++k == word.size()) return true;
        board[i][j] = 'X';
        int dx[] = {1, 0, -1, 0};
        int dy[] = {0, 1, 0, -1};
        for (int s = 0; s != 4; ++s) {
            int new_i = i + dy[s], new_j = j + dx[s];
            if (inBoard(board, new_i, new_j) 
                && board[new_i][new_j] == word[k] 
                && search(board, new_i, new_j, word, k)) {
                board[i][j] = word[--k];
                return true;
            }
        }
        board[i][j] = word[--k];
        return false;
    }

    bool inBoard(vector<vector<char>>& board, int i, int j) {
        int row = board.size(), col = board[0].size();
        return i < row && i >= 0 && j < col && j >= 0;
    }
};

正如上面分析的那样,这种基于哈希表的算法,每次只查询一个单词,显然这会导致重复工作。所以正确的做法是构造一个字典树(Trie Tree),将字典树作为一个待查询的字符串集,在board中进行查找。

毋庸置疑,基于字典树的算法每次都查询整个字符串集,避免了相同前缀多次搜索的问题。字典树的实现请见Leetcode208-Implement Trie (Prefix Tree)

这里我在Leetcode208的基础上做了一些变化:

  • 不使用bool类型的isTail来标识word的末尾。而用string*指针指向words中的单词。原因在于,当知道到达一个待查询单词的末尾时,需要将它加入answer中,显然isTail只能告诉我们到了末尾,却不能告诉我们单词是什么。
  • 本题构造的字典树不需要search(key)方法。因为此处的字典树是待查询的字符串集,而非被查询的字典。
  • 使用了新的c++语法。
  • 搜索路径上同一个字母不能多次使用。因此经过一个board上的节点,都将其标记为‘X’,因为本题承诺所有的输入都是小写字母,所以这样没有问题。在递归结束时需要将board上标记为'X'的点都复原

AC代码

int find(char letter) { return static_cast<int> (letter - 'a'); }

class TrieNode {
public:
    string * wordLocation;
    TrieNode * letters[26];

    TrieNode() {
        wordLocation = NULL;
        for (int i = 0; i != 26; ++i) { letters[i] = NULL; }
    }
};

class WordsDictionary {
public:
    WordsDictionary(): root(new TrieNode()) {}

    void addWord(string& word) {
        TrieNode * curr = root;

        for (int i = 0; i != word.size(); ++i) {
            int index = find(word[i]);
            if (!curr->letters[index]) {
                curr->letters[index] = new TrieNode();
            }
            curr = curr->letters[index];
        }
        curr->wordLocation = &word;
    }

    TrieNode* root;
};

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> answer;
        WordsDictionary wordsDict;
        unordered_set<string> check;
        int row = board.size(), col = board[0].size();

        for (string& word : words) {
            wordsDict.addWord(word);
        }

        for (int i = 0; i != row; ++i) {
            for (int j = 0; j != col; ++j) {
                findWordsInBoard(board, i, j, wordsDict.root, answer, check);
            }
        }

        return answer;
    }

    void findWordsInBoard(vector<vector<char>>& board, int i, int j, TrieNode * curr, vector<string>& answer, unordered_set<string>& check) {
        if (!inBoard(board, i, j) || board[i][j] == 'X') return;

        char currentLetter = board[i][j];
        int dx[] = {1, 0, -1, 0};
        int dy[] = {0, 1, 0, -1};
        int index = find(currentLetter);
        board[i][j] = 'X';

        if (curr->letters[index]) {
            string * location = curr->letters[index]->wordLocation;
            if (location && check.find(*location) == check.end()) {
                answer.push_back(*curr->letters[index]->wordLocation);
                check.insert(*location);
            }
            for (int k = 0; k != 4; ++k) {
                findWordsInBoard(board, i + dy[k], j + dx[k], curr->letters[index], answer, check);
            }
        }
        board[i][j] = currentLetter;
    }

    bool inBoard(vector<vector<char>>& board, int i, int j) {
        int row = board.size();
        int col = board[0].size();

        return i >= 0 && i < row && j >= 0 && j < col;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容