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<vector<char>>& board, string word) {
if (board.empty() || board[].empty()) return false;
int m = board.size(), n = board[].size();
vector<vector<bool>> visited(m, vector<bool>(n));
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (search(board, word, , i, j, visited)) return true;
}
}
return false;
}
bool search(vector<vector<char>>& board, string word, int idx, int i, int j, vector<vector<bool>>& visited) {
if (idx == word.size()) return true;
int m = board.size(), n = board[].size();
if (i < || j < || i >= m || j >= n || visited[i][j] || board[i][j] != word[idx]) return false;
visited[i][j] = true;
bool res = search(board, word, idx + , i - , j, visited)
|| search(board, word, idx + , i + , j, visited)
|| search(board, word, idx + , i, j - , visited)
|| search(board, word, idx + , i, j + , visited);
visited[i][j] = false;
return res;
}
};

我们还可以不用 visited 数组,直接对 board 数组进行修改,将其遍历过的位置改为井号,记得递归调用完后需要恢复之前的状态,参见代码如下:

解法二:

class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (board.empty() || board[].empty()) return false;
int m = board.size(), n = board[].size();
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (search(board, word, , i, j)) return true;
}
}
return false;
}
bool search(vector<vector<char>>& board, string word, int idx, int i, int j) {
if (idx == word.size()) return true;
int m = board.size(), n = board[].size();
if (i < || j < || 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 + , i - , j)
|| search(board, word, idx + , i + , j)
|| search(board, word, idx + , i, j - )
|| search(board, word, idx + , i, j + );
board[i][j] = c;
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/79

类似题目:

Word Search II

参考资料:

https://leetcode.com/problems/word-search/

https://leetcode.com/problems/word-search/discuss/27658/Accepted-very-short-Java-solution.-No-additional-space.

https://leetcode.com/problems/word-search/discuss/27829/C++-backtracking-solution-without-extra-data-structure

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Word Search 词语搜索的更多相关文章

  1. [LeetCode] 79. Word Search 词语搜索

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  2. [LeetCode] Word Search II 词语搜索之二

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  3. [LeetCode] 79. Word Search 单词搜索

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  4. Leetcode: word search

    July 6, 2015 Problem statement: Word Search Given a 2D board and a word, find if the word exists in ...

  5. LeetCode: Word Search 解题报告

    Word SearchGiven a 2D board and a word, find if the word exists in the grid. The word can be constru ...

  6. [LeetCode OJ] Word Search 深度优先搜索DFS

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  7. LeetCode 79. Word Search单词搜索 (C++)

    题目: Given a 2D board and a word, find if the word exists in the grid. The word can be constructed fr ...

  8. [leetcode]Word Search @ Python

    原题地址:https://oj.leetcode.com/problems/word-search/ 题意: Given a 2D board and a word, find if the word ...

  9. [Leetcode] word search 单词查询

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

随机推荐

  1. 深入浅出数据仓库中SQL性能优化之Hive篇

    转自:http://www.csdn.net/article/2015-01-13/2823530 一个Hive查询生成多个Map Reduce Job,一个Map Reduce Job又有Map,R ...

  2. scrapy cookies:将cookies保存到文件以及从文件加载cookies

    我在使用scrapy模拟登录新浪微博时,想将登录成功后的cookies保存到本地,下次加载它实现直接登录,省去中间一系列的请求和POST等.关于如何从本次请求中获取并在下次请求中附带上cookies的 ...

  3. 如何在SSM项目配置springMVC校验框架validator

    1.在springMVC配置文件配置添加如下信息 <!-- 表单验证框架 --> <bean id="validator" class="org.spr ...

  4. .NET 实现并行的几种方式(一)

    好久没有更新了,今天来一篇,算是<同步与异步>系列的开篇吧,加油,坚持下去(PS:越来越懒了). 一.Thread 利用Thread 可以直接创建和控制线程,在我的认知里它是最古老的技术了 ...

  5. Entity Framework 教程——模型浏览器

    模型浏览器: 在之前的章节中,我们创建了第一个关于学校的实体数据模型.但是EDM设计器并没有将他所创建的所有对象完全显示出来.它只将数据库中的被选择的表与视图显示出来了. 模型浏览器可以将EDM所创建 ...

  6. 使用Adminlite + ASP.NET MVC5(C#) + Entityframework + AutoFac + AutoMapper写了个api接口文档管理系统

    一.演示: 接口查看:http://apidoc.docode.top/ 接口后台:http://apiadmin.docode.top/ 登录:administrator,123456 二.使用到的 ...

  7. svn 提交代码报错

    svn 提交代码报错 最近新安装了TortoiseSvn 1.92,在上传代码,其中有新增加的文件,出现如下错误: 解决方法: 1.用vs生成patch文件 2.生成的patch文件中讲nonexis ...

  8. Monkey Patch/Monkey Testing/Duck Typing/Duck Test

    Monkey Patch Monkey Testing Duck Typing Duck Test

  9. 如何实现一个php框架系列文章【6】mysql数据库

    实现一个mysql数据库封装需要考虑的问题 使用方便性 采用直接sql语句操作方式.只要会写sql语句,那么将没有其他学习成本. uctphp框架提供的dba辅助封装类,用会之后将爱不释手. 使用前需 ...

  10. java 开发模式

    Java-开发模式 Java Web开发方案有多种,这里列举一些经典的开发模式进行横向比较JSP+JAVABEAN开发模式:    特点:该模式将业务逻辑与页面表现进行分离,在一定程度上增加了程序的可 ...