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. .net工具类

    ConvertHelper public class ConvertHelper { /// <summary> /// 转换类型 /// </summary> /// < ...

  2. .NET 开源SqlServer ORM框架 SqlSugar 3.0 API

    3.1.x ,将作为3.X系统的最后一个版本,下面将会开发 全新的功能 更新列表:https://github.com/sunkaixuan/SqlSugar/releases 优点: SqlSuga ...

  3. .NET 实现并行的几种方式(二)

    本随笔续接:.NET 实现并行的几种方式(一) 四.Task 3)Task.NET 4.5 中的简易方式 在上篇随笔中,两个Demo使用的是 .NET 4.0 中的方式,代码写起来略显麻烦,这不 .N ...

  4. c3p0连接数据库的3种方式

    c3p0连接数据库的3种方式,这里以mysql为例 1. 直接用set方法设置参数, 基本方法 ComboPooledDataSource dataSource = new ComboPooledDa ...

  5. 【CLR via C#】CSC将源代码编译成托管模块

    下图展示了编译源代码文件的过程.如图所示,可用支持 CLR 的任何一种语言创建源代码文件.然后,用一个对应的编译器检查语法和分析源代码.无论选用哪一个编译器,结果都是一个托管模块(managedmod ...

  6. Placeholder如何换行

    使用js动态添加标签充,处理换行问题 var placeholder = 'This is a line \nthis should be a new line'; $('textarea').att ...

  7. Cleave.js – 自动格式化表单输入框的文本内容

    Cleave.js 有一个简单的目的:帮助你自动格式输入的文本内容. 这个想法是提供一个简单的方法来格式化您的输入数据以增加输入字段的可读性.通过使用这个库,您不需要编写任何正则表达式来控制输入文本的 ...

  8. CoordinatorLayout, AppBarLayout, CollapsingToolbarLayout使用

    本文介绍Design Support Library中CoordinatorLayout, AppBarLayout, CollapsingToolbarLayout的使用. 先列出了Design S ...

  9. Andriod 自定义控件之创建可以复用的组合控件

    前面已学习了一种自定义控件的实现,是Andriod 自定义控件之音频条,还没学习的同学可以学习下,学习了的同学也要去温习下,一定要自己完全的掌握了,再继续学习,贪多嚼不烂可不是好的学习方法,我们争取学 ...

  10. IOS 杂笔-15(知识小点 readonly)

    readonly是我们并不陌生的属性. 但是他也有值得我们注意的地. 属性如其名-只读-也就是说我们只能读取-不能进行写操作 当我们尝试进行写操作时会如下 但是这并不意味着我们不可以改变其内部的属性 ...