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 findWords(vector>& board, vector& words) {
        Trie trie = new Trie();
        vector res;
        string item = "";
        vector> visited;
        for (auto word : words)
            trie.insert(word);
        int m = board.size();
        int n = board[0].size();
        for (int i=0; i>& board, vector &res, string item, int x, int y, vector> &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;
    }
};

你可能感兴趣的:(Word Search II)