回溯法
# 回溯法 MARTRIX = [ 'a', 'b', 't', 'g', 'c', 'f', 'c', 's', 'j', 'd', 'e', 'h', ] def hasPathCore(martrix: list, rows: int, cols: int, s: str, row: int, col: int, pathLenth: int, visited: list): if pathLenth == len(s): return True hasPath = False if (row >= 0 and row < rows and col >= 0 and col<cols and martrix[row * cols + col] == s[pathLenth] and not visited[row * cols + col]): pathLenth += 1 visited[row * cols + col] = True # 左 # 上 # 右 # 下 hasPath = hasPathCore(martrix, rows, cols, s, row, col - 1, pathLenth, visited) or \ hasPathCore(martrix, rows, cols, s, row + 1, col, pathLenth, visited) or \ hasPathCore(martrix, rows, cols, s, row, col + 1, pathLenth, visited) or \ hasPathCore(martrix, rows, cols, s, row - 1, col, pathLenth, visited) # 回溯 if (not hasPath): pathLenth -= 1 visited[row * cols + col] = False return hasPath def hasPath(martrix: list, rows: int, cols: int, s: str): if not martrix or rows < 1 or cols < 1 or not s: return False global visited, pathLenth visited = [False for _ in range(rows * cols)] pathLenth = 0 for row in range(rows): for col in range(cols): if (hasPathCore(martrix, rows, cols, s, row, col, pathLenth, visited)): return True del visited return False print(hasPath(MARTRIX, 3, 4, 'acjde'))