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 =

[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

给定一个2维的字母board,判断 是否有一个网格路径组成给定的单词。

解法:DFS, 典型的深度优先遍历,对每一点的每一条路径进行深度遍历,遍历过程中一旦出现:

1.数组越界。2.该点已访问过。3.该点的字符和word对应的index字符不匹配。

就要对该路径进行剪枝:

Java:

public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length; boolean result = false;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(dfs(board,word,i,j,0)){
result = true;
}
}
} return result;
} public boolean dfs(char[][] board, String word, int i, int j, int k){
int m = board.length;
int n = board[0].length; if(i<0 || j<0 || i>=m || j>=n){
return false;
} if(board[i][j] == word.charAt(k)){
char temp = board[i][j];
board[i][j]='#';
if(k==word.length()-1){
return true;
}else if(dfs(board, word, i-1, j, k+1)
||dfs(board, word, i+1, j, k+1)
||dfs(board, word, i, j-1, k+1)
||dfs(board, word, i, j+1, k+1)){
return true;
}
board[i][j]=temp;
} return false;
} 

Java:

class Solution {
int[] dh = {0, 1, 0, -1};
int[] dw = {1, 0, -1, 0}; public boolean exist(char[][] board, String word) {
boolean[][] isVisited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[0].length; j++)
if (isThisWay(board, word, i, j, 0, isVisited)) return true;
return false;
} public boolean isThisWay(char[][] board, String word, int row, int column, int index, boolean[][] isVisited) {
if (row < 0 || row >= board.length || column < 0 || column >= board[0].length
|| isVisited[row][column] || board[row][column] != word.charAt(index))
return false; //剪枝
if (++index == word.length()) return true; //word所有字符均匹配上
isVisited[row][column] = true;
for (int i = 0; i < 4; i++)
if (isThisWay(board, word, row + dh[i], column + dw[i], index, isVisited))
return true; //以board[row][column]为起点找到匹配上word路径
isVisited[row][column] = false; //遍历过后,将该点还原为未访问过
return false;
}
}  

Python:

class Solution:
# @param board, a list of lists of 1 length string
# @param word, a string
# @return a boolean
def exist(self, board, word):
visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))] for i in xrange(len(board)):
for j in xrange(len(board[0])):
if self.existRecu(board, word, 0, i, j, visited):
return True return False def existRecu(self, board, word, cur, i, j, visited):
if cur == len(word):
return True if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j] or board[i][j] != word[cur]:
return False visited[i][j] = True
result = self.existRecu(board, word, cur + 1, i + 1, j, visited) or\
self.existRecu(board, word, cur + 1, i - 1, j, visited) or\
self.existRecu(board, word, cur + 1, i, j + 1, visited) or\
self.existRecu(board, word, cur + 1, i, j - 1, visited)
visited[i][j] = False return result

C++:

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

类似题目:

[LeetCode] 212. Word Search II 词语搜索 II

[LeetCode] 348. Design Tic-Tac-Toe 设计井字棋游戏

All LeetCode Questions List 题目汇总

  

[LeetCode] 79. Word Search 单词搜索的更多相关文章

  1. 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 ...

  2. [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 ...

  3. leetcode 79. Word Search 、212. Word Search II

    https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...

  4. 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 ...

  5. LeetCode 79 Word Search(单词查找)

    题目链接:https://leetcode.com/problems/word-search/#/description 给出一个二维字符表,并给出一个String类型的单词,查找该单词是否出现在该二 ...

  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. 079 Word Search 单词搜索

    给定一个二维面板和一个单词,找出该单词是否存在于网格中.这个词可由顺序相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格.同一个单元格内的字母不允许被重复使用.例如,给定 二 ...

  8. Leetcode79. Word Search单词搜索

    给定一个二维网格和一个单词,找出该单词是否存在于网格中. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相邻或垂直相邻的单元格.同一个单元格内的字 ...

  9. Leetcode#79 Word Search

    原题地址 依次枚举起始点,DFS+回溯 代码: bool dfs(vector<vector<char> > &board, int r, int c, string ...

随机推荐

  1. 读react源码准备

    git源码地址:https://github.com/facebook/react react 里面就是 react源码 react里面的react文件夹就是react源码,react源码非常的少,总 ...

  2. P2606 [ZJOI2010]排列计数

    P2606 [ZJOI2010]排列计数 因为每个结点至多有一个前驱,所以我们可以发现这是一个二叉树.现在我们要求的就是以1为根的二叉树中,有多少种情况,满足小根堆的性质. 设\(f(i)\)表示以\ ...

  3. python通过json读写序列类型的数据文件

    import json class a: def writeReadJson(self): list2 =['] with open("test.txt",'w') as f: j ...

  4. 项目Alpha冲刺(团队)-第八天冲刺

    格式描述 课程名称:软件工程1916|W(福州大学) 作业要求:项目Alpha冲刺(团队) 团队名称:为了交项目干杯 作业目标:描述第八天冲刺的项目进展.问题困难.心得体会 队员姓名与学号 队员学号 ...

  5. Hive优化(整理版)

    1. 概述 1.1 hive的特征: 可以通过SQL轻松访问数据的工具,从而实现数据仓库任务,如提取/转换/加载(ETL),报告和数据分析: 它可以使已经存储的数据结构化: 可以直接访问存储在Apac ...

  6. 1.zookeeper是干什么的?

    Zookeeper是Hadoop的一个子项目,虽然源自hadoop,但是我发现zookeeper脱离hadoop的范畴开发分布式框架的运用越来越多.今天我想谈谈zookeeper,本文不谈如何使用zo ...

  7. vue cli4.0 快速搭建项目详解

    搭建项目之前,请确认好你自己已经安装过node, npm, vue cli.没安装的可以参考下面的链接安装. 如何安装node? 安装好node默认已经安装好npm了,所以不用单独安装了. 如何安装v ...

  8. [Ignatius and the Princess III] 整数的无序拆分(DP + 生成函数)

    整数的有序拆分就是隔板法,无序拆分则有两种处理方法 DP递推 我们假设P(n,m)P(n,m)P(n,m)是正整数nnn无序拆分为mmm个正整数的方案数 对于某一种拆分,不妨将拆分出来的mmm个数从小 ...

  9. 是Mscoreei.dll的正确版本吗?

    在安装.NET 4.0或更高版本之后,您可能会注意到.NET进程有点不寻常.下面是用.NET 2.0编译器编译的简单“Hello World”可执行文件的加载模块的部分列表. 开始-结束模块名称 60 ...

  10. 选择排序python实现

    选择排序(Selection sort)是一种简单直观的排序算法.它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完.注意每次查找 ...