132. 单词搜索 II

中文
English

给出一个由小写字母组成的矩阵和一个字典。找出所有同时在字典和矩阵中出现的单词。一个单词可以从矩阵中的任意位置开始,可以向左/右/上/下四个相邻方向移动。一个字母在一个单词中只能被使用一次。且字典中不存在重复单词

样例

样例 1:

输入:["doaf","agai","dcan"],["dog","dad","dgdg","can","again"]
输出:["again","can","dad","dog"]
解释:
d o a f
a g a i
d c a n
矩阵中查找,返回 ["again","can","dad","dog"]。

样例 2:

输入:["a"],["b"]
输出:[]
解释:
a
矩阵中查找,返回 []。

挑战

使用单词查找树来实现你的算法

DIRECTIONS = [(0, -1), (0, 1), (-1, 0), (1, 0)]

class Solution:
"""
@param board: A list of lists of character
@param words: A list of string
@return: A list of string
"""
def wordSearchII(self, board, words):
if board is None or len(board) == 0:
return [] word_set = set(words)
prefix_set = set()
for word in words:
for i in range(len(word)):
prefix_set.add(word[:i + 1]) result = set()
for i in range(len(board)):
for j in range(len(board[0])):
c = board[i][j]
self.search(
board,
i,
j,
board[i][j],
word_set,
prefix_set,
set([(i, j)]),
result,
) return list(result) def search(self, board, x, y, word, word_set, prefix_set, visited, result):
if word not in prefix_set:
return if word in word_set:
result.add(word) for delta_x, delta_y in DIRECTIONS:
x_ = x + delta_x
y_ = y + delta_y if not self.inside(board, x_, y_):
continue
if (x_, y_) in visited:
continue visited.add((x_, y_))
self.search(
board,
x_,
y_,
word + board[x_][y_],
word_set,
prefix_set,
visited,
result,
)
visited.remove((x_, y_)) def inside(self, board, x, y):
return 0 <= x < len(board) and 0 <= y < len(board[0])

注意使用prefix hash map来剪枝。

使用trie的解法:

DIRECTIONS = [(0, -1), (0, 1), (-1, 0), (1, 0)]

class TrieNode:    		#定义字典树的节点
def __init__(self):
self.children = {}
self.is_word = False
self.word = None class Trie:
def __init__(self):
self.root = TrieNode() def add(self, word): #字典树插入单词
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode() #在此节点申请节点
node = node.children[c] #继续遍历
node.is_word = True
node.word = word #存入单词 def find(self, word):
node = self.root
for c in word:
node = node.children.get(c)
if node is None:
return None return node class Solution:
"""
@param board: A list of lists of character
@param words: A list of string
@return: A list of string
"""
def wordSearchII(self, board, words):
if board is None or len(board) == 0:
return [] trie = Trie()
for word in words: #插入单词
trie.add(word) result = set()
for i in range(len(board)): #遍历字母矩阵,将每个字母作为单词首字母开始搜索
for j in range(len(board[0])):
c = board[i][j]
self.search(
board,
i,
j,
trie.root.children.get(c),
set([(i, j)]),
result,
) return list(result) def search(self, board, x, y, node, visited, result): #在字典树上dfs查找
if node is None:
return if node.is_word:
result.add(node.word) for delta_x, delta_y in DIRECTIONS: #向四个方向查找
x_ = x + delta_x
y_ = y + delta_y if not self.inside(board, x_, y_):
continue
if (x_, y_) in visited:
continue visited.add((x_, y_))
self.search(
board,
x_,
y_,
node.children.get(board[x_][y_]),
visited,
result,
)
visited.remove((x_, y_)) def inside(self, board, x, y):
return 0 <= x < len(board) and 0 <= y < len(board[0])

dfs 解决(隐式)图搜索问题的更多相关文章

  1. uva 10274 Fans and Gems(隐式图搜索+模拟)

    Fans and Gems Input: Standard Input Output: Standard Output Tomy's fond of a game called 'Fans and G ...

  2. [HNOI2006]最短母串问题 --- AC自动机 + 隐式图搜索

    [HNOI2006]最短母串问题 题目描述: 给定n个字符串(S1,S2.....,Sn),要求找到一个最短的字符串T,使得这n个字符串(S1,S2,......,Sn)都是T的子串. 输入格式: 第 ...

  3. UVa 658 - It's not a Bug, it's a Feature!(Dijkstra + 隐式图搜索)

    链接: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  4. 紫书 例题 11-6 UVa 658 (状态压缩+隐式图搜索+最短路)

    这道题用到了很多知识点, 是一道好题目.      第一用了状态压缩, 因为这里最多只有20位, 所以可以用二进制来储存状态 (要对数据范围敏感), 然后 涉及到了一些位运算.     第二这里是隐式 ...

  5. 【uva 658】It's not a Bug, it's a Feature!(图论--Dijkstra或spfa算法+二进制表示+类“隐式图搜索”)

    题意:有N个潜在的bug和m个补丁,每个补丁用长为N的字符串表示.首先输入bug数目以及补丁数目.然后就是对M个补丁的描述,共有M行.每行首先是一个整数,表明打该补丁所需要的时间.然后是两个字符串,第 ...

  6. 洛谷 P2622 关灯问题II【状压DP;隐式图搜索】

    题目描述 现有n盏灯,以及m个按钮.每个按钮可以同时控制这n盏灯--按下了第i个按钮,对于所有的灯都有一个效果.按下i按钮对于第j盏灯,是下面3中效果之一:如果a[i][j]为1,那么当这盏灯开了的时 ...

  7. UVA_10603 倒水问题 隐式图搜索

    这道题目是刘汝佳白书上的例题,没有LRJ在白书上提到的划归为搜索问题,还真是一时难以想到好的解法.即三个瓶子,任意的一个状态都是一个节点,最后就划归为一个搜索问题. 由于题目数据量不大,三个杯子容量都 ...

  8. uva 310 L--system(隐式图搜索+字符串处理)

     L-system  A D0L (Deterministic Lindenmayer system without interaction) system consists of a finite ...

  9. 状态转移的最短路 隐式图搜索 UVA 658

    紫书365 题目大意:给你n个全都是bug的东西,然后每次可以修复,给你修复前后的状态,问最后如果能把bug全都修复,最少需要多少时间. 思路:从最初状态开始,然后枚举bug即可. 表示priorit ...

  10. uva-321-暴力枚举-隐式图搜索

    题意:给你n个房间,有许多灯的控制开关,i房间灯的开关在j房间,未开灯的房间不能进,i房间和j房间之间如果没有门,也不能从i进入到j,开始房间是1,并且灯是开着的,问你是否能够走到最后一个房间n,并且 ...

随机推荐

  1. Unittest 类方法

    import unittest,time from selenium import webdriver class TestClass(unittest.TestCase): @classmethod ...

  2. Linux中文件权限查看和修改

    权限定义 linux文件权限分为:r读权限(4).w写权限(2).x执行权限(1) linux权限对象分为:拥有者.组用户.其他用户 权限修改: chown user:group /usr/local ...

  3. Zookeeper connection loss leads to Flink job restart

    Flink可以使用zookeeper来进行ha,而一般我们都会使用zookeeper的高级api架构curator来对zk进行通讯.在curator中引入了状态的概念,包括connected,reco ...

  4. Springboot Actuator之十:actuator中的audit包

    前言这篇文章我们来分析一下org.springframework.boot.actuate.security,org.springframework.boot.actuate.audit中的代码,这2 ...

  5. 避免maven package 打包时执行 mybatis-generator-maven-plugin 插件

    一.为什么打包时会执行该插件mybatis-generator-maven-plugin默认绑定了package的生命周期 二.如何解决如果在package和install 执行插件,修改pom中的配 ...

  6. SQL Server 中获取一个表的字段信息

    直接贴代码了: SELECT sysobjects.name AS TableName, syscolumns.Id AS TableId, syscolumns.name AS DbColumnNa ...

  7. 【拆分版】Docker-compose构建Kibana单实例,基于7.1.0

    写在前边 今凌晨的时候已经把这整个Docker-compose构建的ELK集群跑起来了,有点没熬住,所以早上起来补文档,今天就上到公司测试服务器上测试了,好开森. 本文内容就是红框的部分,只是启动个K ...

  8. PHP7.3.0+弃用FILTER_FLAG_SCHEME_REQUIRED的解决办法

    今天本地调用一个接口报错了: filter_var(): explicit use of FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIR ...

  9. lightGBM gpu环境配置

    推荐先看一手官方的Installation Guide.我用的是ubuntu 16.04,一些要求如下图: 主要是OpenCL以及libboost两个环境的要求. (1) OpenCL的安装.我这里之 ...

  10. Implementing Azure AD Single Sign-Out in ASP.NET Core(转载)

    Let's start with a scenario. Bob the user has logged in to your ASP.NET Core application through Azu ...