【LeetCode】79. Word Search 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/word-search/description/
题目描述
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.
题目大意
在一个二维表格里面,看看能不能连续的一笔画出word这个词。
解题方法
回溯法
还是经典的回溯法问题。这个题的回溯的起点可以是二维数组的任意位置。
回溯法的判定条件比较简单,需要注意的是把已经走过的路给改变了,不能再走了。python中通过swapcase()交换该字母的大小写即可行。
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for y in xrange(len(board)):
for x in xrange(len(board[0])):
if self.exit(board, word, x, y, 0):
return True
return False
def exit(self, board, word, x, y, i):
if i == len(word):
return True
if x < 0 or x >= len(board[0]) or y < 0 or y >= len(board):
return False
if board[y][x] != word[i]:
return False
board[y][x] = board[y][x].swapcase()
isexit = self.exit(board, word, x + 1, y, i + 1) or self.exit(board, word, x, y + 1, i + 1) or self.exit(board, word, x - 1, y, i + 1) or self.exit(board, word, x, y - 1, i + 1)
board[y][x] = board[y][x].swapcase()
return isexit
使用C++的话,新开辟了一个visited数组,代表是否已经访问过了。总体代码不难。我使用了pair来保存位置,所以代码略显长了一些。
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (word.size() == 0) return false;
const int M = board.size(), N = board[0].size();
vector<vector<bool>> visited(M, vector<bool>(N, false));
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j ++) {
if (dfs(board, word, 0, {i, j}, visited)) {
return true;
}
}
}
return false;
}
bool dfs(const vector<vector<char>>& board, const string& word, int start, pair<int, int> curpos, vector<vector<bool>>& visited) {
const int M = board.size(), N = board[0].size();
if (start == word.size()) return true;
if (curpos.first < 0 || curpos.first >= M || curpos.second < 0 || curpos.second >= N || visited[curpos.first][curpos.second] || word[start] != board[curpos.first][curpos.second])
return false;
visited[curpos.first][curpos.second] = true;
for (auto d : dirs) {
int nx = curpos.first + d.first;
int ny = curpos.second + d.second;
if (dfs(board, word, start + 1, {nx, ny}, visited))
return true;
}
visited[curpos.first][curpos.second] = false;
return false;
}
private:
vector<pair<int, int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
};
日期
2018 年 2 月 27 日
2018 年 12 月 22 日 —— 今天冬至
【LeetCode】79. Word Search 解题报告(Python & C++)的更多相关文章
- [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: Word Search 解题报告
Word SearchGiven a 2D board and a word, find if the word exists in the grid. The word can be constru ...
- [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#79 Word Search
原题地址 依次枚举起始点,DFS+回溯 代码: bool dfs(vector<vector<char> > &board, int r, int c, string ...
- 【LeetCode】Word Break 解题报告
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...
- 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 ...
随机推荐
- Office2020-2021 离线安装教程
首先:先安装两个 net .再安装 office 如下: DownFile:https://pan.baidu.com/s/19iykxwofXK36wWY5w4GVFg codenum:6666
- 分布式服务治理框架Dubbo的前世今生及应用实战
Dubbo的出现背景 Dubbo从开源到现在,已经出现了接近10年时间,在国内各大企业被广泛应用. 它到底有什么魔力值得大家去追捧呢?本篇文章给大家做一个详细的说明. 大规模服务化对于服务治理的要求 ...
- Go Robot
1 <html> 2 <meta http-equiv="Content-Type" content="text/html; charset=utf-8 ...
- Spark中的分区方法详解
转自:https://blog.csdn.net/dmy1115143060/article/details/82620715 一.Spark数据分区方式简要 在Spark中,RDD(Resilien ...
- 【Reverse】每日必逆0x03
BUU-刮开有奖 附件:https://files.buuoj.cn/files/abe6e2152471e1e1cbd9e5c0cae95d29/8f80610b-8701-4c7f-ad60-63 ...
- 【编程思想】【设计模式】【行为模式Behavioral】command
Python版 https://github.com/faif/python-patterns/blob/master/behavioral/command.py #!/usr/bin/env pyt ...
- 什么是javaScript闭包
闭包是与函数有着紧密的关系,它是函数的代码在运行过程中的一个动态环境,是一个运行期的概念. 所谓闭包,是指词法表示包括不必计算的变量的函数.也就是说,该函数能够使用函数外定义的变量. 在程序语言中,所 ...
- VUE3 之 生命周期函数
1. 概述 老话说的好:天生我材必有用,千金散尽还复来. 言归正传,今天我们来聊一下 VUE 的生命周期函数. 所谓生命周期函数,就是在某一条件下被自动触发的函数. 2. VUE3 生命周期函数介绍 ...
- OAuth2.0实战:认证、资源服务异常自定义!
大家好,我是不才陈某~ 这是<Spring Security 进阶>的第4篇文章,往期文章如下: 实战!Spring Boot Security+JWT前后端分离架构登录认证! 妹子始终没 ...
- shell脚本 监控网卡信息
一.简介 源码地址 日期:2018/6/22 介绍:显示实时输入输出流量 效果图: 二.使用 适用:centos6+ 语言:英文 注意:无 下载 wget https://raw.githubuser ...