回溯以找到所有可能的路径

2024-03-29 05:05:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在最近的一次采访中问到这个问题

给定一个字母和一个单词,找出所有可能的路径 说一句话

方向:水平、垂直或对角线到距离为1的任何坐标

约束:每条路径必须是一组唯一的坐标。在

示例:

S T A R
A R T Y
X K C S
T R A P

START - > 2

这是我的解决方案

class WordFinder:
    def __init__(self):
        self.neighbors = [[-1, 1], [0, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [0, 1], [1, 1]]

    def find_all_paths(self, grid, word):
        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == word[0]:
                    visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
                    result = []
                    self.helper(grid, 0, 0, visited, word, 0, result)
                    count += len(result)
        return count

    def helper(self, grid, row, col, visited, word, index, result):
        if index == len(word):
            result.append(1)
        adjacent = []
        for item in self.neighbors:
            adjacent.append([row + item[0], col + item[1]])
        for adj in adjacent:
            if 0 <= adj[0] < len(grid) and 0 <= adj[1] < len(grid[0]):
                if not visited[adj[0]][adj[1]]:
                    if index + 1 < len(word) and grid[adj[0]][adj[1]] == word[index + 1]:
                        visited[adj[0]][adj[1]] = True
                        self.helper(grid, adj[0], adj[1], visited, word, index + 1, result)
                        visited[adj[0]][adj[1]] = False


if __name__ == '__main__':
    word_finder = WordFinder()
    print(word_finder.find_all_paths(
        [['s', 't', 'a', 'r'], ['a', 'r', 't', 'y'], ['x', 'k', 'c', 's'], ['t', 'r', 'a', 'p']],
        "start"))

这就产生了错误的答案。有人能帮我理解我的逻辑问题吗。在


Tags: inselfhelperforindexlenifdef
1条回答
网友
1楼 · 发布于 2024-03-29 05:05:46

答案应该是4,不是2,对吗?我对“所有可能的路径”和“唯一的坐标集”的解释是,同一个坐标不能在单个路径中重复使用,但不同的路径可能使用其他路径的坐标。在

    Paths (row, col):
path1:    0 0   0 1   1 0   1 1    1 2
path2:    0 0   0 1   0 2   1 1    1 2
path3:    0 0   0 1   1 0   0 3    1 2    
path4:    2 3   1 2   0 2   1 1    0 1

我看到3个虫子,可能还有更多:

  1. @user3386109指出

    在自己的邻居=[[-1,1],[0,-1],[1,-1],[1,0],[1,0],[1,1],[0,1],[1,1]]

应该是

^{pr2}$
  1. 每次从0,0开始:

    在自我帮助者(网格,0,0,已访问,word,0,结果)

应该是:

self.helper(grid, i, j, visited, word, 0, result)
  1. 您的终止在1:

    如果索引==长度(字):

应该是

if index == len(word) - 1:

相关问题 更多 >