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. php内核分析(六)-opcode

    这里阅读的php版本为PHP-7.1.0 RC3,阅读代码的平台为linux 查看opcode php是先把源码解析成opcode,然后再把opcode传递给zend_vm进行执行的. // 一个op ...

  2. 列表组件抽象(2)-listViewBase说明

    这是我写的关于列表组件的第2篇博客.前面的相关文章有: 1. 列表组件抽象(1)-概述 listViewBase是列表组件所有文件中最核心的一个,它抽象了所有列表的公共逻辑,将来如果有必要添加其它公共 ...

  3. asp.net core 依赖注入问题

    最近.net core可以跨平台了,这是一个伟大的事情,为了可以赶上两年以后的跨平台部署大潮,我也加入到了学习之列.今天研究的是依赖注入,但是我发现一个问题,困扰我很久,现在我贴出来,希望可以有人帮忙 ...

  4. PDF编辑神器

    转自网络 http://files.cnblogs.com/files/quejuwen/pdfeditportable.zip

  5. css水平居中的各种方法

    说到水平居中,大家可能觉得很简单啊,text-align:center 就OK了. 但是,有时候会发现这样写了也没出效果.原因是什么呢?  请往下看. 水平居中:分为块级元素居中和行元素居中 行内元素 ...

  6. Maven远程仓库的配置

    在很多情况下,默认的中央仓库无法满足项目的需求,可能项目需要的构件存在于另外一个远程仓库中,如JBoss Maven仓库.这时,可以在POM中配置该仓库,见代码如下: <!-- 远程仓库的配置 ...

  7. GJM :Unity集成Leap Motion

        Demo演示视频

  8. 详细介绍Mysql各种存储引擎的特性以及如何选择存储引擎

    最近业务上有要求,要实现类似oracle 的dblink   linux版本 Server version: 5.6.28-0ubuntu0.14.04.1 (Ubuntu) 修改配置文件 /etc/ ...

  9. js picker webapp仿ios picker

    iosselect 在webapp下的一个picker组件 可以轻松实现各类选择器效果.比如地区选择 时间选择 日期选择等. 可以定制依赖关系,可以定制选择层级,可以定制高度 展示项数.无论你是px还 ...

  10. win7的6个网络命令

    1 名称: Ipconfig 参数: /all : 显示详细信息 /renew: 更新所有适配器 /renew EL*:更新所有名称以EL为开头的连接 /release *Con*: 释放所有匹配的连 ...