797 所有可能的路徑

2022-07-11 18:33:07 字數 1456 閱讀 6040

**一:dfs回溯

class solution(object):

# 方法一:dfs

def allpathssourcetarget(self, graph):

""":type graph: list[list[int]]

:rtype: list[list[int]]

"""if not graph[0]:

return

res =

n = len(graph)

self.dfs(graph, 0, n - 1, [0], res)

return res

def dfs(self, graph, cur, end, temp, res):

# 遞迴出口:當前節點是n-1時,說明找到一條新路徑

if temp[-1] == end:

return

# 順著當前節點往下走

for i in graph[cur]:

self.dfs(graph, i, end, temp + [i], res)

class solution(object):

def allpathssourcetarget(self, graph):

""":type graph: list[list[int]]

:rtype: list[list[int]]

"""# 特判

if not graph[0]:

return

# 路徑終點

end = len(graph) - 1

res =

# 佇列初始化

nodequeue = [0]

pathqueue = [[0]]

while nodequeue:

node = nodequeue.pop(0)

path = pathqueue.pop(0)

# 遍歷當前節點能達到的所有節點

for i in graph[node]:

# 若當前節點是終點,則找到一條新路徑

if i == end:

# 否則,當前節點先入隊,並更新當前路徑

else:

return res

Leetcode 797 所有可能的路徑 C

給乙個有 n 個結點的有向無環圖,找到所有從 0 到 n 1 的路徑並輸出 不要求按順序 輸入 1,2 3 3 輸出 0,1,3 0,2,3 解釋 圖是這樣的 0 1 v v 2 3 這有兩條路 0 1 3 和 0 2 3.dfs深搜回溯,從節點0開始遍歷,終點為n 1。詳細過程見 vectorin...

133 所有可能的路徑

題目描述 給乙個有 n 個結點的有向無環圖,找到所有從 0 到 n 1 的路徑並輸出 不要求按順序 結點的數量會在範圍 2,15 內。你可以把路徑以任意順序輸出,但在路徑內的結點的順序必須保證。使用回溯和遞迴進行 class solution public static void dfspath l...

988 211所有學校

console 命令列 function removetablerow rowlist,rownum var ptn211 new regexp 清華大學 北京大學 中國人民大學 北京工業大學 北京理工大學 北京航空航天大學 北京化工大學 北京郵電大學 對外經濟 大學 中國傳媒大學 民族大學 中國礦...