【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.

Example:

Input: 
board = [
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
words = ["oath","pea","eat","rain"]

Output: ["eat","oath"]

Note:

All inputs are consist of lowercase letters a-z.
The values of words are distinct.

思路

思路一:dfs,搜索每个单词。容易超时,要注意姿势。
思路二:建立一棵树,把所有的单词加到树上。从board的所有位置开始,在树上搜索,所有能搜到的单词加入到ans中。

代码

代码一:

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        n = board.size();
        m = board[0].size();
        vector<string> res;
        for (int i=0; i<words.size(); ++i) {
            if (find_(board, words[i]))
                res.push_back(words[i]);
        } 
        return res;
    }
    
private:
    int stx, sty;
    int n, m;
    
    bool find_(vector<vector<char>>& board, string& word) {    
        for (int i=0; i<n; ++i) {
            for (int j=0; j<m; ++j) {
                if (dfs(board, word, i, j, 0)) return true;
            }
        }
        return false;
    }

    vector<int> dir {1, 0, -1, 0, 1};
    
    bool dfs(vector<vector<char>>& board, string& word, int x, int y, int index) {
        if (x < 0 || x >= n || y < 0 || y >= m) return false;
        if (board[x][y] != word[index]) return false;
        if (index == word.length()-1) return true;
        
        bool flag;
        char ch = board[x][y];
        board[x][y] = '#';
        flag = dfs(board, word, x+1, y, index+1) ||
               dfs(board, word, x, y+1, index+1) || 
               dfs(board, word, x-1, y, index+1) ||
               dfs(board, word, x, y-1, index+1);
        board[x][y] = ch;
        return flag;
    }
};

代码二:

class TrieNode{
public:
    vector<TrieNode*> nodes;
    const string* word;
    TrieNode():nodes(26), word(nullptr) {}
    ~TrieNode() {
        for (auto node : nodes) delete node;
    }
};

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        TrieNode root;
        for (const string& word : words) {
            TrieNode* cur = &root;
            for (char c : word) {
                auto& next = cur->nodes[c-'a'];
                if (!next) next = new TrieNode();
                cur = next;
            }
            cur->word = &word;
        }
        n = board.size();
        m = board[0].size();
        
        for (int i=0; i<n; ++i) {
            for (int j=0; j<m; ++j) {
                dfs(i, j, &root, board);
            }
        }
        return ans;
    }
    
private:
    int n, m;
    vector<string> ans;
    void dfs(int x, int y, TrieNode* node, vector<vector<char>>& board) {
        if (x < 0 || x >= n || y < 0 || y >= m) return;
        if (board[x][y] == '#') return;
        char cur = board[x][y];
        TrieNode* nxtnode = node->nodes[cur-'a'];
        if (!nxtnode) return;
        
        if (nxtnode->word) {
            ans.push_back(*nxtnode->word);
            nxtnode->word = nullptr;
        }
        
        board[x][y] = '#';
        dfs(x+1, y, nxtnode, board);
        dfs(x-1, y, nxtnode, board);
        dfs(x, y+1, nxtnode, board);
        dfs(x, y-1, nxtnode, board);
        board[x][y] = cur;
        return;
    }
};
发布了323 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104942896