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,并且 ...
随机推荐
- SUSE12.2 编译usbutils
折腾了两天,终于交叉编译出来lsusb命令可以在单板上跑起来,记录一下 1:编译eudev下载地址:https://dev.gentoo.org/~blueness/eudev/,版本eudev-3. ...
- Oracle_PLSQL导出导入dmp文件
地址:F:\app\duling\product\11.2.0\dbhome_1\BIN\imp.exe ----------------------------------------------- ...
- 监听浏览器tab选项卡选中事件,点击浏览器tab标签页回调事件,浏览器tab切换监听事件
js事件注册代码: <script> document.addEventListener('visibilitychange',function(){ //浏览器tab切换监听事件 if( ...
- 【07月03日】A股ROE最高排名
个股滚动ROE = 最近4个季度的归母净利润 / ((期初归母净资产 + 期末归母净资产) / 2). 查看更多个股ROE最高排名 兰州民百(SH600738) - ROE_TTM:86.45% - ...
- 一场Math.Round函数的误解
有不少人误将Math.Round函数当作四舍五入函数在处理, 结果往往不正确, 实际上Math.Round采用的是国际通行的是 Banker 舍入法. Banker's rounding(银行家舍入) ...
- Linux内核device结构体分析
1.前言 Linux内核中的设备驱动模型,是建立在sysfs设备文件系统和kobject上的,由总线(bus).设备(device).驱动(driver)和类(class)所组成的关系结构,在底层,L ...
- ubuntu 17.04 下搭建深度学习环境
.目前使用CPU即可,先不需要显卡配置 .使用pip3 安装深度学习框架 .要先安装pip3 #sudo apt install python3-pip https://blog.csdn.net/b ...
- Sitecore 8.2 防火墙规则的权威指南
如今,使用多层安全保护您的数据不再是奢侈品; 这是不容谈判的.此外,您需要确保Sitecore解决方案保持运行并与集成服务(例如SQL,Mongo,Solr)通信,同时保持相同的安全级别. 让我们假设 ...
- 【数据结构与算法】线性表操作(C语言)
#include <stdio.h> #include <stdlib.h> #define OK 1 #define NO 0 #define MAXSIZE 20 type ...
- ipv4的ip字符串转化为int型
要求: 将现有一个ipv4的ip字符串(仅包含数字,点,空格), 其中数字和点之间的空格(至多一个)是合法的,比如“12 .3. 4 .62”,其他情况均为非法地址.写一个函数将ipv4地址字符串转化 ...