【发布时间】:2020-01-18 16:37:22
【问题描述】:
我正在编写一个算法来检查二维数组是否具有字符序列。我的算法适用于水平和垂直搜索,但不适用于对角线:
board = [
['Z', 'B', 'N', 'O', 'N', 'O'],
['Z', 'B', 'O', 'N', 'N', 'Z'],
['B', 'O', 'B', 'B', 'N', 'B'],
['O', 'N', 'O', 'N', 'N', 'N'],
['Z', 'Z', 'Z', 'Z', 'B', 'O'],
['B', 'Z', 'O', 'Z', 'B', 'N']
]
def dfs(board, word):
if not board:
return False
N,M = len(board), len(board[0])
stack = []
for i in range(N):
for j in range(M):
if board[i][j] == word[0]:
stack.append((i,j,0,{(i,j)}))
while stack:
i,j,step,visit=stack.pop()
step+=1
if step==len(word):
return True
for (ni,nj) in [(i+x,j+y) for x,y in [(0,1), (0, -1), (1,0), (-1,0)]]:
if (ni,nj) not in visit and 0<=ni<N and 0<=nj<M and board[ni][nj] == word[step]:
stack.append((ni,nj,step,visit.union({(ni,nj)})))
return False
对于输入 ZZZZ、NNNN 和 OOOO,我的函数 DFS 应该返回 True,但 OOOO 不起作用 - 对角线步骤不起作用。
我该如何解决?
【问题讨论】:
-
您只有一种情况需要解决(例如从左上角开始的对角线),因为所有其他三种情况都可以通过相同的算法访问,并且只需左右、上下或两个都。而且您可能可以根据搜索的字符串的长度进一步限制(我已经看到这个基于 TicTacToe 的示例在采访中要求)
标签: python algorithm depth-first-search