Leetcode -- Word Search II
2015-10-26 21:42
405 查看
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 =
Return
Note:
You may assume that all inputs are consist of lowercase letters
分析:
本题采用trie结构求解,可以降低运算量。有关trie的相关内容参考 点击打开链接有关内容。
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.
分析:
本题采用trie结构求解,可以降低运算量。有关trie的相关内容参考 点击打开链接有关内容。
class Solution { public: set<string> res; Trie trie; int dif[4][2]={{0,-1},{0,1},{-1,0},{1,0}}; int n,m; void dfs(vector<vector<char>>& board,vector<vector<bool>> vis,string cur,int x,int y) { if(trie.search(cur)) res.insert(cur); vis[x][y]=1; for(int i=0;i<4;++i) { int xx=x+dif[i][0],yy=y+dif[i][1]; if(xx>=0&&xx<n&&yy>=0&&yy<m&&vis[xx][yy]==0) { if(trie.startsWith(cur+board[xx][yy])) dfs(board,vis,cur+board[xx][yy],xx,yy); } } } vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { for(int i=0;i<words.size();++i) trie.insert(words[i]); n=board.size(),m=board[0].size(); vector<vector<bool>> vis(n,vector<bool>(m,0)); for(int i=0;i<n;++i) for(int j=0;j<m;++j) { string s; s+=board[i][j]; if(trie.startsWith(s)) dfs(board,vis,s,i,j); } vector<string> final; for(auto &str:res) final.push_back(str); return final; } };
相关文章推荐
- hdu1114Piggy-Bank【完全背包基础题】
- ALM测试
- 高级学员:2015年10月26日作业
- ALM测试
- Volley及FastJson的简单使用
- 我5年总结出的14条编程经验
- SQL基础(三)之约束
- svn: E155019: Can't upgrade as it is not a pre-1.7 work解决办法
- 【[R] 【教程】教你如何读懂线性回归lm的结果summary(判断显著性)[转]】
- Qt中 QGLWidget碰到no such file or directory的解决办法
- C语言-函数指针和指针函数
- 图的基本操作
- Spring MVC 中的 @ResponseBody 注解的使用场合
- Hive原理与不足
- hdu 4614 Vases and Flowers(线段树)
- 【开篇】心态、责任比技术能力更重要
- VideoView的全屏问题
- 常用的SQL语句(牢记)
- 《一切都是最好的安排》——加措
- python的文件和流