https://www.cnblogs.com/grandyang/p/4332313.html

在一个矩阵中能不能找到string的一条路径

这个题使用的是dfs。但这个题与number of islands有点不同,那个题中visited过的就不用再扫了,但是这个需要进行回溯回来。

所以使用了visited[i][j] = false;

本质区别还是那个题是找一片区域,这个题更像是找一条路径。

错误一:如果board不引用,会报超内存

错误二:

这个写法和正确写法基本相同,但错误写法需要每次都去遍历flag1、flag2、flag3、flag4,正确写法中,如果flag1为真,就不用再去遍历flag2、3、4,这样就节省了许多时间。

所以这个写法报的错误是在有一个比较大的case超时。

https://blog.csdn.net/CV2017/article/details/82659742

或运算符,左右两边通常为关系或相等表达式,第一个操作数将完全运算,仅当第一个操作数的计算结果为 false 时计算第二个操作数,当第一个操作数的计算结果为 true 时,不用计算第二个操作数和这之后的操作数,直接运行后面的代码了

class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[].size();
vector<vector<bool> > visited(m,vector<bool>(n));
for(int i = ;i < m;i++){
for(int j = ;j < n;j++){
int index = ;
if(exit(board,word,i,j,index,visited))
return true;
}
}
return false;
} bool exit(vector<vector<char>>& board,string word,int i,int j,int index,vector<vector<bool>>& visited){
if(index == word.size())
return true;
if(i < || i >= board.size() || j < || j >= board[].size() || visited[i][j] == true || board[i][j] != word[index])
return false;
visited[i][j] = true;
bool flag1 = exit(board,word,i - ,j,index+,visited);
bool flag2 = exit(board,word,i + ,j,index+,visited);
bool flag3 = exit(board,word,i,j - ,index+,visited);
bool flag4 = exit(board,word,i,j + ,index+,visited);
visited[i][j] = false;
return flag1 || flag2 || flag3 || flag4; }
};

正确写法:

如果第一个字符不相同,就继续遍历,这个操作可以减少搜索的个数

vector<vector<bool>> visited(m,vector<bool>(n,false));不要写在for循环里面,其实每次递归都是将置为true的又置为了false的。

class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[].size();
vector<vector<bool> > visited(m,vector<bool>(n,false));
for(int i = ;i < m;i++){
for(int j = ;j < n;j++){
if(board[i][j] != word[])
continue;
int index = ;
if(exit(board,word,i,j,index,visited))
return true;
}
}
return false;
} bool exit(vector<vector<char>>& board,string word,int i,int j,int index,vector<vector<bool>>& visited){
if(index == word.size())
return true;
if(i < || i >= board.size() || j < || j >= board[].size() || visited[i][j] == true || board[i][j] != word[index])
return false;
visited[i][j] = true;
bool res = exit(board,word,i - ,j,index+,visited) || exit(board,word,i + ,j,index+,visited) || exit(board,word,i,j - ,index+,visited) || exit(board,word,i,j + ,index+,visited);
visited[i][j] = false;
return res; }
};

212. Word Search II

https://www.cnblogs.com/grandyang/p/4516013.html

这个题是trie树与dfs相结合的题目,将所有需要搜索的词存入trie树当中,然后在二维数组中dfs搜索。

这个题的trie树的定义和leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design的不太一样,208、211定义了一个isWord

用来表示是否是词的结尾。这个题定义的则是一个string,并且这个string存储的就是整个单词,这样既可以用来表示结尾,又可以获得搜索的整个词。这样做主要是由于

这个题目本身要求返回搜索成功的词。

这个题在搜索到词后,还需要clear掉str,因为题目要求同一个词只返回一个,例子如下:

Input:
[["a","a"]]
["a"]
Output:
["a","a"]
Expected:
["a"]

class Solution {
public:
struct TrieNode{
TrieNode* child[];
string str;
TrieNode():str(""){
for(int i = ;i < ;i++)
child[i] = NULL;
}
};
struct Trie{
TrieNode* root;
Trie():root(new TrieNode()){
}
void insert(string s){
TrieNode* p = root;
for(char tmp : s){
int i = tmp - 'a';
if(!p->child[i])
p->child[i] = new TrieNode();
p = p->child[i];
}
p->str = s;
return;
}
};
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
if(board.empty() || board[].empty() || words.empty())
return res;
int m = board.size(),n = board[].size();
Trie T;
for(string word : words)
T.insert(word);
vector<vector<bool>> visited(m,vector<bool>(n,false));
for(int i = ;i < m;i++){
for(int j = ;j < n;j++){
if(T.root->child[board[i][j] - 'a'])
findWords(board,T.root->child[board[i][j] - 'a'],visited,i,j,res);
}
}
return res;
}
void findWords(vector<vector<char>>& board,TrieNode* p,vector<vector<bool>>& visited,int i,int j,vector<string>& res){
if(!p->str.empty()){
res.push_back(p->str);
p->str.clear();
}
visited[i][j] = true;
for(auto dir : dirs){
int x = i + dir[];
int y = j + dir[];
if(x < || x >= board.size() || y < || y >= board[].size() || visited[x][y] == true || p->child[board[x][y] - 'a'] == NULL)
continue;
findWords(board, p->child[board[x][y] - 'a'],visited, x, y, res);
}
visited[i][j] = false;
return;
}
private:
vector<vector<int>> dirs{{-,},{,},{,-},{,}};
};

leetcode 79. Word Search 、212. Word Search II的更多相关文章

  1. Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)

    Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...

  2. python如何转换word格式、读取word内容、转成html

    # python如何转换word格式.读取word内容.转成html? import docx from win32com import client as wc # 首先将doc转换成docx wo ...

  3. leetcode@ [79/140] Trie树应用 Word Search / Word Search II

    https://leetcode.com/problems/word-search/ class Solution { public: struct Trie{ Trie *next[]; bool ...

  4. leetcode 139. Word Break 、140. Word Break II

    139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...

  5. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

  6. leetcode 169. Majority Element 、229. Majority Element II

    169. Majority Element 求超过数组个数一半的数 可以使用hash解决,时间复杂度为O(n),但空间复杂度也为O(n) class Solution { public: int ma ...

  7. leetcode 54. Spiral Matrix 、59. Spiral Matrix II

    54题是把二维数组安卓螺旋的顺序进行打印,59题是把1到n平方的数字按照螺旋的顺序进行放置 54. Spiral Matrix start表示的是每次一圈的开始,每次开始其实就是从(0,0).(1,1 ...

  8. leetcode 263. Ugly Number 、264. Ugly Number II 、313. Super Ugly Number 、204. Count Primes

    263. Ugly Number 注意:1.小于等于0都不属于丑数 2.while循环的判断不是num >= 0, 而是能被2 .3.5整除,即能被整除才去除这些数 class Solution ...

  9. leetcode 344. Reverse String 、541. Reverse String II 、796. Rotate String

    344. Reverse String 最基础的旋转字符串 class Solution { public: void reverseString(vector<char>& s) ...

随机推荐

  1. 图解数据库中的各种 JOIN

    本文转载至https://mazhuang.org/2017/09/11/joins-in-sql/#full-outer-join-excluding-inner-join,如需阅读原文请至上述链接 ...

  2. idou老师教你学Istio 27:解读Mixer Report流程

    1.概述 Mixer是Istio的核心组件,提供了遥测数据收集的功能,能够实时采集服务的请求状态等信息,以达到监控服务状态目的. 1.1 核心功能 •前置检查(Check):某服务接收并响应外部请求前 ...

  3. BCB 编写服务程序的一个注意事项

      BCB编写服务,install报错的一个问题 今天编写了一个服务,最后INSTALL 的时候报错,如图: 经过近1小时的比较(俺过去写例子),居然无意中设置了一个属性               ...

  4. Java并发包--ArrayBlockingQueue

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/3498652.html ArrayBlockingQueue介绍 ArrayBlockingQueue是数 ...

  5. C指针乱记

    //int a[3][4] = { { 66, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; //读取二维数组任意元素hint int(*)a[4] ...

  6. BZOJ 3576: [Hnoi2014]江南乐 (SG函数)

    题意 有nnn堆石子,给定FFF,每次操作可以把一堆石子数不小于FFF的石子平均分配成若干堆(堆数>1>1>1). 平均分配即指分出来的石子数中最大值减最小值不超过111.不能进行操 ...

  7. redis在应用中使用连接不释放问题解决

    今天测试,发现redis使用的时候,调用的链接一直不释放.后查阅蛮多资料,才发现一个配置导致的.并不是他们说的服务没有启动导致的. 1)配置文件 #redis连接配置================= ...

  8. 【题解】在你窗外闪耀的星星-C++

    题目题目描述飞逝的的时光不会模糊我对你的记忆.难以相信从我第一次见到你以来已经过去了3年.我仍然还生动地记得,3年前,在美丽的集美中学,从我看到你微笑着走出教室,你将头向后仰,柔和的晚霞照耀着你玫瑰色 ...

  9. npm源管理

    1. 安装淘宝镜像 为了提高npm的安装速度,可以使用淘宝镜像. 使用淘宝镜像的方法有两种: 1. npm install -g cnpm --registry=https://registry.np ...

  10. myeclipse打开jsp后死掉,或变卡的问题

    很多小伙伴在myeclipse下打开jsp会特别卡,甚至会卡死掉,我也遇到过很多次这种情况,下面分享一下解决方法: 1,打开 Window -> Preferences -> Genera ...