[leedcode 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.

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"].

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
      /*  刚看到题目想到之前有一道Word Search,所以马上想到暴力搜索每一个单词,但是很不幸跟预想的一样超时了,看了一下hint,提到了字典树。所以先用所给的单词来构建字典树,然后在dfs搜索字典树中的单词,这样就避免了大量的重复比较。另外如果搜索的路径已经不是字典树是的前缀了就可以直接剪枝返回了。下面是AC代码。因为要避免重复,我先用了一个set存结果,然后再转存到result中。*/
    }
};

 

posted @ 2015-08-06 10:42  ~每天进步一点点~  阅读(105)  评论(0编辑  收藏  举报