作者: 负雪明烛
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++)的更多相关文章

  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 解题报告

    Word SearchGiven a 2D board and a word, find if the word exists in the grid. The word can be constru ...

  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 79. Word Search 、212. Word Search II

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

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

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

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

  7. Leetcode#79 Word Search

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

  8. 【LeetCode】Word Break 解题报告

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

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

随机推荐

  1. 通过yum安装 memcache

    . 通过yum安装 复制代码代码如下: yum -y install memcached#安装完成后执行:memcached -h#出现memcached帮助信息说明安装成功 2. 加入启动服务 复制 ...

  2. 为什么重写equals必须重写hashCode

    目录 equals常见面试题 为什么要重写equals 重写equals不重写hashCode会存在什么问题 总结 equals常见面试题 在开始聊之前,我们先看几个常见的面试题,看看你能不能都回答上 ...

  3. javaSE高级篇6 — 注解( 附:注解底层解析 ) —— 更新完毕

    注解 ---- 英文:annotation 1.注解长什么样子? @xxxxxxx( 一些信息 ) ----- 这个信息可有可无 2.注解可以放在什么地方? 类本身的上面.属性的上面.方法的上面.参数 ...

  4. java类加载、对象创建过程

    类加载过程: 1, JVM会先去方法区中找有没有相应类的.class存在.如果有,就直接使用:如果没有,则把相关类的.class加载到方法区 2, 在.class加载到方法区时,会分为两部分加载:先加 ...

  5. Qt最好用评价最高的是哪个版本?

    来源: http://www.qtcn.org/bbs/read-htm-tid-89455.html /// Qt4:    4.8.7      4.X 系列终结版本 Qt5 :   5.6 LT ...

  6. 零基础学习java------day17------缓冲字节流,转换字节流,简化流,缓冲字符流,序列化和对象流

    1. 缓冲字节流 缓冲区:缓冲区实质上是一个数组.通常它是一个字节数组,但是也可以使用其他种类的数组.但是一个缓冲区不 仅仅 是一个数组.缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/写进程 ...

  7. Vue相关,diff算法。

    1. 当数据发生变化时,vue是怎么更新节点的? 要知道渲染真实DOM的开销是很大的,比如有时候我们修改了某个数据,如果直接渲染到真实dom上会引起整个dom树的重绘和重排,有没有可能我们只更新我们修 ...

  8. Linux学习 - 目录表

    目录名 作用 权限 说明 /bin/ 存放系统命令的目录 所有用户 存放在/bin/下的命令单用户模式下也可以执行 /sbin/ 保存和系统环境设置相关的命令 root                 ...

  9. jquery的each和js原生for循环性能对比

    <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> &l ...

  10. clickhouse安装数据导入及查询测试

    官网 https://clickhouse.tech/ quick start ubantu wget https://repo.yandex.ru/clickhouse/deb/lts/main/c ...