我正在尝试解决此问题:
给定一个n * m的矩阵,该矩阵包含字母(字符),在矩阵中找到最长的连续字母路径并输出字符串。例如:
m = [[a,c,d],[i,b,e],[h,g,f]]
result = e,f,g,h
您只能在矩阵内向上,向下,向左,向右移动。到目前为止,这是我在网上了解一些信息后提出的,但是我还没有达到目标。 我还想提高解决方案的效率,我当前的代码可能有太多的循环,对于大型矩阵来说可能很慢。任何帮助将不胜感激!
R = len(matrix)
C = len(matrix[0])
x = [0, 1, 0, -1]
y = [1, 0, -1, 0]
dp=[[0 for i in range(C)]for i in range(R)]
def isvalid( i, j):
if (i < 0 or j < 0 or i >= R or j >= C):
return False
return True
def getLenUtil(matrix, i, j, prev):
if (isvalid(i, j)==False or isadjacent(prev, mat[i][j])==False):
return 0
if (dp[i][j] != -1):
return dp[i][j]
ans = 0
for k in range(4):
ans = max(ans, 1 + getLenUtil(mat, i + x[k],j + y[k], mat[i][j]))
dp[i][j] = ans
return dp[i][j]
def isadjacent(prev, curr):
if (ord(curr) -ord(prev)) == 1:
return True
return False
def findLongestSequence(matrix):
for i in range(R):
for j in range(C):
dp[i][j]=-1
ans = 0
for i in range(R):
for j in range(C):
if (mat[i][j] == s):
for k in range(4):
ans = max(ans, 1 + getLenUtil(matrix, i + x[k], j + y[k], s));
return ans
答案 0 :(得分:1)
代码中的几个问题:
mat
和matrix
的拼写应该统一。s
从未初始化R = len(matrix)
和其他对mat
或matrix
的引用中,未定义该变量。用实际值findLongestSequence
调用matrix
,因此应该在那里定义R
,... etc 也是
prev
,而是通过实际的 expected 字符(已经“递增”),则比较容易。dp
,然后用-1重新初始化?只需立即使用-1。这是它的工作方式:
def findLongestSequence(mat):
R = len(mat)
C = len(mat[0])
x = [0, 1, 0, -1]
y = [1, 0, -1, 0]
dp = [[-1 for i in range(C)] for i in range(R)]
def isvalid( i, j):
return (0 <= i < R) and (0 <= j < C)
def getLenUtil(mat, i, j, expected):
if not isvalid(i, j) or mat[i][j] != expected:
return 0
if dp[i][j] == -1:
ans = 0
expected = chr(ord(mat[i][j])+1)
for k in range(4):
ans = max(ans, 1 + getLenUtil(mat, i + x[k], j + y[k], expected))
dp[i][j] = ans
return dp[i][j]
ans = 0
for i in range(R):
for j in range(C):
getLenUtil(mat, i, j, mat[i][j])
ans = max(ans, max(dp[i]))
print(dp)
return ans
res = findLongestSequence([["a","c","d"],["i","b","e"],["h","g","f"]])
print(res)
请注意,对于此示例数据,返回的答案是8,而不是4,因为最长的序列以“ b”开头,以“ i”结尾-总共8个字符。