回溯法

# 回溯法
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'))

 

posted @ 2020-08-26 10:37  烧刘病  阅读(112)  评论(0编辑  收藏  举报
回到页首