python输出随机字母矩阵_Python程序计算我们可以从字母矩阵生成的单词数

假设我们有一个4 x 4的字母板和一个单词列表,我们必须找到可以由一系列相邻字母在面板中生成的单词数量最多,每个单词最多使用一个单元格(但是我们 可以重用单元格来换句话说)。 我们可以向上,向下,向左,向右或对角线方向移动。

所以,如果输入像mbfd

xaya

tztr

sqqq

words = [“ bat”,“ far”,“ mat”],则输出将为3,因为我们可以生成mat [0,1]→[1,1]→[2,0],bat [0, 2]→[1,1]→[2,2],far [0,2]→[1,3]→[2,3]。

范例(Python)

让我们看下面的实现以更好地理解-class Solution:

def solve(self, A, words):

N = len(A)

M = len(A[0])

trie = dict()

for word in words:

current = trie

for c in word:

if c in current:

current = current[c]

else:

current[c] = dict()

current = current[c]

current["*"] = True

ans = 0

def dfs(x, y, d):

nonlocal ans

if "*" in d:

del d["*"]

ans += 1

temp = A[x][y]

A[x][y] = "#"

for i in [x - 1, x, x + 1]:

for j in [y - 1, y, y + 1]:

if 0 <= i 

A[x][y] = temp

for i in range(N):

for j in range(M):

if A[i][j] in trie:

dfs(i, j, trie[A[i][j]])

return ans

ob = Solution()

matrix = [

["m", "b", "f", "d"],

["x", "a", "y", "a"],

["t", "z", "t", "r"],

["s", "q", "q", "q"]

]

words = ["bat", "far", "mat"]

print(ob.solve(matrix, words))

输入值[

["m", "b", "f", "d"],

["x", "a", "y", "a"],

["t", "z", "t", "r"],

["s", "q", "q", "q"] ],

["bat", "far", "mat"]

输出结果3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值