此题采用回溯发来进行求解,在说之前我想告诉大家,如果大家看过之前别人提交的py版本的代码,会发现不能通过全部的测试用例,现在我根据剑指offer书中的思路写下如下py的代码,希望您批评指正!!!
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix or not path :
return False
visited = [0] * len(matrix)
result = ''
length = 0
for row in range(rows):
for col in range(cols):
if (self.hasPathCore(matrix, path, rows, cols, row, col, visited, result, length)):
return True
del visited
return False
def hasPathCore(self, matrix, path, rows, cols, row, col, visited, result, length):
if result == path:
return True
hasPath = False
if (row >= 0 and row < rows and col >= 0 and col < cols and (not visited[row*cols + col])\
and path[length] == matrix[row*cols + col]):
length += 1
visited[row*cols + col] = 1
result += matrix[row*cols + col]
hasPath = self.hasPathCore(matrix, path, rows, cols, row-1, col, visited, result, length) or \
self.hasPathCore(matrix, path, rows, cols, row+1, col, visited, result, length) or \
self.hasPathCore(matrix, path, rows, cols, row, col+1, visited, result, length) or \
self.hasPathCore(matrix, path, rows, cols, row, col-1, visited, result, length)
if (not hasPath):
length -= 1
visited[row*cols + col] = 0
result = result[:-1]
return hasPath
京公网安备 11010502036488号