請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。
路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。
例如 a b c e s f c s a d e e 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字符串的第一個字符b占據了矩陣中的第一行第二個格子之后,路徑不能再次進入該格子。
思路,主函數設計循環從矩陣的每個位置開始調用輔助函數判斷以此位置開始是否有這條路徑。
輔助函數判斷開始位置上下左右移動是否和路徑一致,判斷邊界,出棧之后將路徑記錄重置。
# -*- coding:utf-8 -*- class Solution: def hasPath(self, matrix, rows, cols, path): # write code here if matrix == '' or rows <= 0 or cols <= 0 or path == '': return False #記錄路徑是否走過 flag = [0]*len(matrix) for i in xrange(rows): for j in xrange(cols): #如果有一個路徑滿足,則返回True if self.finPath(matrix, rows, cols, i, j, path, flag, 0): return True del flag return False def finPath(self, matrix, rows, cols, i, j, path, flag, k): index = i * cols + j if i < 0 or j < 0 or i >= rows or j >= cols or k > len(path)-1 or path[k] != matrix[index] or flag[index] == 1: return False #走到最后一位返回True if k == len(path)-1: return True flag[index] = 1 #上下左右 if self.finPath(matrix, rows, cols, i+1, j, path, flag, k+1) or \ self.finPath(matrix, rows, cols, i-1, j, path, flag, k+1) or \ self.finPath(matrix, rows, cols, i, j+1, path, flag, k+1) or \ self.finPath(matrix, rows, cols, i, j-1, path, flag, k+1): return True #出棧重置 flag[index] = 0 #完全出棧還沒有返回值,說明不存在這條路徑 return False so = Solution() matrix = 'ABCESFCSADEE' matrix = ''.join(matrix) path = 'ABCB' path = ''.join(path) print so.hasPath(matrix, 3, 4, path)