[LeetCode212] Word Search II

HARD

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.

click to show hint.

Hide Company Tags Airbnb
Hide Tags Backtracking Trie
Hide Similar Problems (M) Word Search

在第三遍leetcode開始,終於有點做題的感覺了。

Hint: TrieNode.

基本思想:把要搜索的word 都加進TrieTree, 遍歷board 做dfs

很簡單吧?但每一步都需要仔細斟酌。

比如題目要求:The same letter cell may not be used more than once in a word. 這就意味着我們要標記 current char under search 並且在search完要reset 它。

同時, 同樣的word不能push 進我們的result兩次!!這就意味着我們找到一個word就要改變它的isWord flag.

除此之外, 在TrieNode class 的設計上,加了一個int indicates the current word’s position in words list.

code如下:

class TrieNode{
public:
    TrieNode(){
        isWord = false;
        pos = 0;
        for(int i = 0; i<26; ++i)
            neighbors[i] = NULL;
    }
    bool isWord;
    int pos;
    TrieNode* neighbors[26];
};
class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        TrieNode* root = makeTrie(words);
        int m = board.size(), n = board[0].size(), wordCnt = words.size();
        vector<string> res;
        for(int i = 0; i<m; ++i){
            for(int j = 0; j<n && wordCnt > res.size(); ++j){// by using wordCnt> res.size() we can end the loop early.
                searchDFS(board, i, j, root, res, words);
            }
        }
        return res;
    }

    void searchDFS(vector<vector<char>>& board, int row, int col, TrieNode* node, vector<string>& res,vector<string>& words){
        int m = board.size(), n = board[0].size();
        if(row >= m || col >=n || row < 0 || col < 0 || board[row][col] == 'X'|| !node->neighbors[board[row][col] - 'a']) return;
        char c = board[row][col];
        if(node->neighbors[c - 'a']->isWord){
            res.push_back(words[node->neighbors[c-'a']->pos]);
            node->neighbors[c - 'a']->isWord = false;// avoid pushing duplicates.
        }
        board[row][col] = 'X';// mark current char is visited, every char can be used only once
        vector<pair<int, int>> dir = {{row + 1, col}, {row - 1, col}, {row,col+1}, {row, col - 1}};
        for(auto d : dir){
            searchDFS(board, d.first, d.second, node->neighbors[c - 'a'], res, words);
        }
        board[row][col] = c;// recover current char 
    }

    TrieNode* makeTrie(vector<string>& words){
        TrieNode* root = new TrieNode();
        for(int i = 0; i < words.size(); ++i){
            TrieNode* p = root;
            for(char c : words[i]){
                if(!p->neighbors[c - 'a']) p->neighbors[c - 'a'] = new TrieNode();
                p = p->neighbors[c - 'a'];
            }
            p->isWord = true;
            p->pos = i;
        }
        return root;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章