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.

偷偷看了下hint,说是用字典树,然后我想了想,应该是第一个节点是空,然后把board中出现的节点作为第二层节点,然后排排排,然后再遍历words看看是否在树中出现。但是我还是不会写。感觉不是很难,不过树的构建。

看了下答案,发现自己想错了,应该把words建树,然后dfs遍历board。

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        Trie trie = new Trie();
        vector<string> res;
        string item = "";
        vector<vector<bool>> visited;
        for (auto word : words)
            trie.insert(word);
        int m = board.size();
        int n = board[0].size();
        for (int i=0; i<m; i++)
            for (int j=0; j<n; j++) {
                dfs(board, res, item, i, j, visited, trie);
            }
        return res;
    }
    
    void dfs(vector<vector<char>>& board, vector<string> &res, string item, int x, int y, vector<vector<bool>> &visited, Trie trie())
    {
        if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size())
            return;
        if (visited[x][y])
            return;
        item += board[x][y];
        if (!startWith(item))
            return;
        if (trie.find(item))
            res.push_back(item);
        visited[x][y] = true;
        dfs(board, res, item, x-1, y, visited, trie);
        dfs(board, res, item, x+1, y, visited, trie);
        dfs(board, res, item, x, y-1, visited, trie);
        dfs(board, res, item, x, y+1, visited, trie);
        visited[x][y] = false;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容