題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之后不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字符串的第一個字符b占據了矩陣中的第一行第二個格子之后,路徑不能再次進入該格子。
拙見:
回溯的思想。
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
visited = [True for i in range(rows*cols)]
k = 0
length = len(path)
for i in range(rows*cols):
if self.hasPathNext(matrix, visited, path, rows, cols, i/cols, i%cols, k, length):
return True
return False
def hasPathNext(self, matrix, visited, path, rows, cols, i, j, k, length):
if k > length-1:
return True
if i>=0 and i<rows and j>=0 and j<cols and visited[i*cols+j] and matrix[i*cols+j]==path[k]:
k += 1
visited[i*cols+j] = False
if self.hasPathNext(matrix, visited, path, rows, cols, i, j-1, k, length) or self.hasPathNext(matrix, visited, path, rows, cols, i+1, j, k, length) or self.hasPathNext(matrix, visited, path, rows, cols, i, j+1, k, length) or self.hasPathNext(matrix, visited, path, rows, cols, i-1, j, k, length):
return True
else:
k -= 1
visited[i*cols+j] = True
return False
else:
return False
牛油高見:
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
for i in range(rows):
for j in range(cols):
if matrix[i*cols+j] == path[0]:
if self.find(list(matrix),rows,cols,path[1:],i,j):
return True
return False
def find(self,matrix,rows,cols,path,i,j):
if not path:
return True
matrix[i*cols+j]='0'
if j+1<cols and matrix[i*cols+j+1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j+1)
elif j-1>=0 and matrix[i*cols+j-1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j-1)
elif i+1<rows and matrix[(i+1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i+1,j)
elif i-1>=0 and matrix[(i-1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i-1,j)
else:
return False