C++怎么实现词语搜索
这篇文章主要介绍了C++怎么实现词语搜索的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C++怎么实现词语搜索文章都会有所收获,下面我们一起来看看吧。
专注于为中小企业提供网站建设、成都网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业汨罗免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上1000+企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
Word Search 词语搜索
Given a 2D board and a word, find if the word exists in the grid.
The word can 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.
For example,
Given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
这道题是典型的深度优先遍历 DFS 的应用,原二维数组就像是一个迷宫,可以上下左右四个方向行走,我们以二维数组中每一个数都作为起点和给定字符串做匹配,我们还需要一个和原数组等大小的 visited 数组,是 bool 型的,用来记录当前位置是否已经被访问过,因为题目要求一个 cell 只能被访问一次。如果二维数组 board 的当前字符和目标字符串 word 对应的字符相等,则对其上下左右四个邻字符分别调用 DFS 的递归函数,只要有一个返回 true,那么就表示可以找到对应的字符串,否则就不能找到,具体看代码实现如下:
解法一:
class Solution { public: bool exist(vector>& board, string word) { if (board.empty() || board[0].empty()) return false; int m = board.size(), n = board[0].size(); vector > visited(m, vector (n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (search(board, word, 0, i, j, visited)) return true; } } return false; } bool search(vector >& board, string word, int idx, int i, int j, vector >& visited) { if (idx == word.size()) return true; int m = board.size(), n = board[0].size(); if (i < 0 || j < 0 || i >= m || j >= n || visited[i][j] || board[i][j] != word[idx]) return false; visited[i][j] = true; bool res = search(board, word, idx + 1, i - 1, j, visited) || search(board, word, idx + 1, i + 1, j, visited) || search(board, word, idx + 1, i, j - 1, visited) || search(board, word, idx + 1, i, j + 1, visited); visited[i][j] = false; return res; } };
我们还可以不用 visited 数组,直接对 board 数组进行修改,将其遍历过的位置改为井号,记得递归调用完后需要恢复之前的状态,参见代码如下:
解法二:
class Solution { public: bool exist(vector>& board, string word) { if (board.empty() || board[0].empty()) return false; int m = board.size(), n = board[0].size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (search(board, word, 0, i, j)) return true; } } return false; } bool search(vector >& board, string word, int idx, int i, int j) { if (idx == word.size()) return true; int m = board.size(), n = board[0].size(); if (i < 0 || j < 0 || i >= m || j >= n || board[i][j] != word[idx]) return false; char c = board[i][j]; board[i][j] = "#"; bool res = search(board, word, idx + 1, i - 1, j) || search(board, word, idx + 1, i + 1, j) || search(board, word, idx + 1, i, j - 1) || search(board, word, idx + 1, i, j + 1); board[i][j] = c; return res; } };
关于“C++怎么实现词语搜索”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C++怎么实现词语搜索”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。
分享标题:C++怎么实现词语搜索
网址分享:http://pwwzsj.com/article/iiiojd.html