簡體   English   中英

像圖形一樣遍歷二維數組

[英]Iterate through 2D array like a graph

我在二維數組中存儲了一個圖形,我想打印從左到右通過組的任何有向圖的所有可能路徑。 我在下面給出了一個示例,並希望打印從第一組(在本例中為 G1)到任何最后一組(在本例中為 G3)的所有路徑。 我無法構建遞歸或遞歸方法來打印具有任意數量組的所有路徑。 所以我需要幫助構建手動迭代系統/算法 謝謝。

graph:

在此處輸入圖片說明

script.py

map = [
  [1,2],
  [3,4,5],
  [6,7]
]

// Print all paths
// Note :- every array in the map is a group

output:

1 -> 3 -> 6
1 -> 3 -> 7
1 -> 4 -> 6
1 -> 4 -> 7
1 -> 5 -> 6
1 -> 5 -> 7
2 -> 3 -> 6
2 -> 3 -> 7
2 -> 4 -> 6
2 -> 4 -> 7
2 -> 5 -> 6
2 -> 5 -> 7

根據描述,您需要在變量“map”中提​​到的所有路徑的可能組合。 所以你可以使用 itertools 來獲取所有可能的路徑組合。

我想這應該適合你:

import itertools
pattern = list(itertools.product(*map))
print(pattern)

輸出

[(1, 3, 6),
(1, 3, 7),
(1, 4, 6),
(1, 4, 7),
(1, 5, 6),
(1, 5, 7),
(2, 3, 6),
(2, 3, 7),
(2, 4, 6),
(2, 4, 7),
(2, 5, 6),
(2, 5, 7)]

這是一個使用遞歸的解決方案,並且不使用庫,它將適用於任何數量的組

mp = [
  [1,2],
  [3,4,5],
  [6,7]
]

def possible_path(M,index,combination):
    for i in M[index]:  
        if index<len(M)-1:
            possible_path(M,index+1,combination+[i])
        else:
            print(combination+[i])

possible_path(mp,0,[])

這是輸出:

[1, 3, 6]
[1, 3, 7]
[1, 4, 6]
[1, 4, 7]
[1, 5, 6]
[1, 5, 7]
[2, 3, 6]
[2, 3, 7]
[2, 4, 6]
[2, 4, 7]
[2, 5, 6]
[2, 5, 7]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM