dfs 解决(隐式)图搜索问题
132. 单词搜索 II
给出一个由小写字母组成的矩阵和一个字典。找出所有同时在字典和矩阵中出现的单词。一个单词可以从矩阵中的任意位置开始,可以向左/右/上/下四个相邻方向移动。一个字母在一个单词中只能被使用一次。且字典中不存在重复单词
样例
样例 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 解决(隐式)图搜索问题的更多相关文章
- uva 10274 Fans and Gems(隐式图搜索+模拟)
Fans and Gems Input: Standard Input Output: Standard Output Tomy's fond of a game called 'Fans and G ...
- [HNOI2006]最短母串问题 --- AC自动机 + 隐式图搜索
[HNOI2006]最短母串问题 题目描述: 给定n个字符串(S1,S2.....,Sn),要求找到一个最短的字符串T,使得这n个字符串(S1,S2,......,Sn)都是T的子串. 输入格式: 第 ...
- 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& ...
- 紫书 例题 11-6 UVa 658 (状态压缩+隐式图搜索+最短路)
这道题用到了很多知识点, 是一道好题目. 第一用了状态压缩, 因为这里最多只有20位, 所以可以用二进制来储存状态 (要对数据范围敏感), 然后 涉及到了一些位运算. 第二这里是隐式 ...
- 【uva 658】It's not a Bug, it's a Feature!(图论--Dijkstra或spfa算法+二进制表示+类“隐式图搜索”)
题意:有N个潜在的bug和m个补丁,每个补丁用长为N的字符串表示.首先输入bug数目以及补丁数目.然后就是对M个补丁的描述,共有M行.每行首先是一个整数,表明打该补丁所需要的时间.然后是两个字符串,第 ...
- 洛谷 P2622 关灯问题II【状压DP;隐式图搜索】
题目描述 现有n盏灯,以及m个按钮.每个按钮可以同时控制这n盏灯--按下了第i个按钮,对于所有的灯都有一个效果.按下i按钮对于第j盏灯,是下面3中效果之一:如果a[i][j]为1,那么当这盏灯开了的时 ...
- UVA_10603 倒水问题 隐式图搜索
这道题目是刘汝佳白书上的例题,没有LRJ在白书上提到的划归为搜索问题,还真是一时难以想到好的解法.即三个瓶子,任意的一个状态都是一个节点,最后就划归为一个搜索问题. 由于题目数据量不大,三个杯子容量都 ...
- uva 310 L--system(隐式图搜索+字符串处理)
L-system A D0L (Deterministic Lindenmayer system without interaction) system consists of a finite ...
- 状态转移的最短路 隐式图搜索 UVA 658
紫书365 题目大意:给你n个全都是bug的东西,然后每次可以修复,给你修复前后的状态,问最后如果能把bug全都修复,最少需要多少时间. 思路:从最初状态开始,然后枚举bug即可. 表示priorit ...
- uva-321-暴力枚举-隐式图搜索
题意:给你n个房间,有许多灯的控制开关,i房间灯的开关在j房间,未开灯的房间不能进,i房间和j房间之间如果没有门,也不能从i进入到j,开始房间是1,并且灯是开着的,问你是否能够走到最后一个房间n,并且 ...
随机推荐
- 认识随机函数rand()和srand(unsigned int )
rand函数 int rand( void ); 函数名: rand 功 能: 随机数发生器 用 法: int rand(void); 所在头文件: stdlib.h 函数说明 : ...
- centos git编译
1. 下载git源码 https://git-scm.com 2. 根据文档一步步操作 https://git-scm.com/book/en/v2/Getting-Started-Installin ...
- 分布式系统全局唯一ID生成
一 什么是分布式系统唯一ID 在复杂分布式系统中,往往需要对大量的数据和消息进行唯一标识. 如在金融.电商.支付.等产品的系统中,数据日渐增长,对数据分库分表后需要有一个唯一ID来标识一条数据或消息, ...
- leetcode 111. 二叉树的最小深度
题目描述: 给定一个二叉树,找出其最小深度. 最小深度是从根节点到最近叶子节点的最短路径上的节点数量. 说明: 叶子节点是指没有子节点的节点. 示例: 给定二叉树 [3,9,20,null,null, ...
- 如何使用 Django中的 get_queryset, get_context_data和 get_object 等方法
原文: https://blog.csdn.net/HH2030/article/details/80994274
- nginx出现403 Forbidden错误
问题描述:将webpack打包的react前端部署到nginx上,发现出现403 Forbidden错误 解决方案:修改nginx.conf文件,添加user root;配置
- SpringBoot 应用篇之从 0 到 1 实现一个自定义 Bean 注册器
191213-SpringBoot 应用篇之从 0 到 1 实现一个自定义 Bean 注册器 我们知道在 spring 中可以通过@Component,@Service, @Repository 装饰 ...
- 解决上传文件或图片时选择相同文件无法触发change事件的问题
昨天在做一个上传文件的模块时遇到了这样的问题:打开文件一上传,上传成功后再次点击文件一,change事件无反应 <input type="file" name="f ...
- 移动端可视化框架antv f2出现两个legend选项
前天遇到个坑,把我给坑死了 ,在帮朋友做一个微信公众号的项目,使用的vue全家桶,有个模块需要用到数据可视化展现,之前做项目的时候用过antv,比较熟悉,因为是移动端的项目,所以用的是antv f2这 ...
- mysql给某个用户单个表权限
CREATE USER systemselect IDENTIFIED BY 'Zbank123456';#只给查询权限 GRANT SELECT ON szkitil.zbank_businesss ...