标签:python bool 示例 copy deepcopy exist items dfs problem
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
[‘A‘,‘B‘,‘C‘,‘E‘],
[‘S‘,‘F‘,‘C‘,‘S‘],
[‘A‘,‘D‘,‘E‘,‘E‘]
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
应该dfs写了个BFS,毛病。deepcopy占用很多时间。
trick
ans = []
for b in board:
ans += b
need = Counter(word)
ans = Counter(ans)
for k, v in need.items():
if v > ans[k]:
return False
import copy
from collections import defaultdict
class Solution:
def exist(self, board, word: str) -> bool:
m = len(board)
n = len(board[0])
stack = []
flags = set([])
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
t = copy.deepcopy(flags)
t.add((i,j))
stack.append((t,(i,j),1))
while len(stack)>0:
#print(stack)
top = stack[-1]
stack = stack[:-1]
t, (i,j), k = top
if k>=len(word):
return True
for p, q in [(0,1),(0,-1),(1,0),(-1,0)]:
if 0<=i+p<m and 0<=j+q<n and (i+p,j+q) not in t and word[k]==board[i+p][j+q]:
new_t = copy.deepcopy(t)
new_t.add((i+p,j+q))
stack.append((new_t,(i+p,j+q),k+1))
return False
标签:python bool 示例 copy deepcopy exist items dfs problem
原文地址:https://www.cnblogs.com/Lzqayx/p/13672619.html