[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 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 单词搜索的更多相关文章
- 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 ...
- [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 ...
- leetcode 79. Word Search 、212. Word Search II
https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...
- 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 ...
- LeetCode 79 Word Search(单词查找)
题目链接:https://leetcode.com/problems/word-search/#/description 给出一个二维字符表,并给出一个String类型的单词,查找该单词是否出现在该二 ...
- [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 ...
- 079 Word Search 单词搜索
给定一个二维面板和一个单词,找出该单词是否存在于网格中.这个词可由顺序相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格.同一个单元格内的字母不允许被重复使用.例如,给定 二 ...
- Leetcode79. Word Search单词搜索
给定一个二维网格和一个单词,找出该单词是否存在于网格中. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相邻或垂直相邻的单元格.同一个单元格内的字 ...
- Leetcode#79 Word Search
原题地址 依次枚举起始点,DFS+回溯 代码: bool dfs(vector<vector<char> > &board, int r, int c, string ...
随机推荐
- zookeeper题目
1. ZooKeeper是什么?2. ZooKeeper提供了什么?3. Zookeeper文件系统4. ZAB协议?5. 四种类型的数据节点 Znode6. Zookeeper Watcher 机制 ...
- 15 分钟学会使用 Git 和远程代码库
Git是个了不起但却复杂的源代码管理系统.它能支持复杂的任务,却因此经常被认为太过复杂而不适用于简单的日常工作.让我们诚实一记吧:Git是复杂的,我们不要装作它不是.但我仍然会试图教会你用(我的)基本 ...
- djiango-异步发送邮件--celery
安装 pip install celery==4.2.0 # celery4.x支持django1.11以上版本 试了好几个版本 就4.2.0能发送成功 1.项目目录里新建一个celery的包cele ...
- UVa11542Squre——异或方程组&&高斯消元法
题意 给出 $n$ 个整数,从中选出1个或多个,使得选出的整数乘积是完全平方数.一共有多少种选法?($1 \leq n \leq 100$,$1 \leq a_i \leq 10^{15}$ 且不含大 ...
- AtCoder Beginner Contest 132 解题报告
前四题都好水.后面两道题好难. C Divide the Problems #include <cstdio> #include <algorithm> using names ...
- freemarker使用shiro标签(spring boot)
freemarker使用shiro标签(spring boot) 2018年07月03日 14:20:37 niu_sayok 阅读数:348更多 个人分类: freeMarkerShiro 首先 ...
- Pandas的基本用法
Pandas是使用python进行数据分析不可或缺的第三方库.我们已经知道,NumPy的ndarray数据结构能够很好地进行数组运算,但是当我们需要进行为数据添加标签,处理缺失值,对数据分组,创建透视 ...
- sublime text 3插件改造之AutoFileName去掉.vue文件中img标签后面的width和height,完全去掉!!
在.vue文件中img标签使用autofilename提示引入文件时,会在文件后面插入宽度高度,如下图: 文件后面会自动插入height和width,其实这两玩意儿在大多数时候并没卵用,然后就开始了百 ...
- render函数、createElement函数与vm.$slots
1.render函数.createElement函数 Vue.component('es-header', { render: function (createElement) { return cr ...
- [bzoj 4833]最小公倍佩尔数
传送门 Description Let \((1+\sqrt2)^n=e(n)+f(n)\cdot\sqrt2\) , both \(e(n)\) and \(f(n)\) are integer ...