单词搜索 II-LintCode
来源:互联网 发布:矩阵理论答案 编辑:程序博客网 时间:2024/06/05 13:25
给出一个由小写字母组成的矩阵和一个字典。找出所有同时在字典和矩阵中出现的单词。一个单词可以从矩阵中的任意位置开始,可以向左/右/上/下四个相邻方向移动。
给出矩阵:
doaf
agai
dcan
和字典:
{“dog”, “dad”, “dgdg”, “can”, “again”}
返回 {“dog”, “dad”, “can”, “again”}
#ifndef C132_H#define C132_H#include<iostream>#include<string>#include<vector>using namespace std;class Solution {public: /** * @param board: A list of lists of character * @param words: A list of string * @return: A list of string */ vector<string> wordSearchII(vector<vector<char> > &board, vector<string> &words) { // write your code here vector<string> v; if (board.empty() || words.empty()) return v; int k = 0; for (auto c : words) { for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[0].size(); ++j) { if (findWord(board, i, j, 0, c)) v.push_back(c); } } } if (v.empty()) return v; else { words.clear(); words.push_back(v[0]); for (int k = 0; k < v.size(); ++k) { if (v[k] != words.back()) words.push_back(v[k]); } return words; } } bool findWord(vector<vector<char>> &v, int i, int j, int pos, string word) { if (pos >= word.size()) return true; if (i < 0 || i >= v.size() || j < 0 || j >= v[0].size() || v[i][j] != word[pos]) return false; v[i][j] ^= 100; bool res= findWord(v, i + 1, j, pos + 1, word) | findWord(v, i - 1, j, pos + 1, word) | findWord(v, i, j + 1, pos + 1, word) | findWord(v,i, j - 1, pos + 1, word); v[i][j] ^= 100; return res; }};#endif
阅读全文
0 0
- LintCode 单词搜索 II
- LintCode : 单词搜索 II
- 单词搜索 II-LintCode
- LintCode 132-单词搜索II 深度优先
- LintCode-单词接龙II
- 单词接龙 II-LintCode
- 单词拆分II-LintCode
- lintcode-单词搜索-123
- lintcode ----单词搜索
- lintcode,单词搜索
- 单词搜索 -LintCode
- lintcode --单词搜索
- 单词搜索 II
- LintCode:搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- 【LintCode】搜索二维矩阵 II
- lintcode,搜索二维矩阵 II
- Lintcode 搜索二维矩阵 II
- 10种优化页面加载速度的方法
- CodeFroces 823B. Petya and Exam(构造题)
- java实现多线程有两种方法:1、集成Thread类、2、实现Runnable接口
- BLE 4.2的新功能加强了隐私和安全,解决了早期BLE的缺陷并且提高了能效
- IOS中使用iframe无法滚动解决办法
- 单词搜索 II-LintCode
- 【Linux】红帽7搭建本地YUM源
- HDU-3038-How Many Answers Are Wrong [带权并查集]
- 多目标优化问题中常见分解方法的理解
- hdu 4568 (状压dp TSP问题)
- 链表面试题之链表相交问题
- 机器学习导论
- HDU 1003 Max Sum
- 逆元粗解