[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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值