像图表一样迭代二维数组

我已将图形存储在二维数组中,并且我想打印从左到右通过组的任何有向图的所有可能路径。我在下面给出了一个示例,并希望打印从第一组(在本示例中为 G1)到任何最后一组(在本示例中为 G3)的所有路径。我无法构建递归或递归方法来打印具有任意数量组的所有路径。所以我需要帮助构建手动迭代系统/算法。谢谢。

graph:

https://img1.sycdn.imooc.com/658a93d90001839802180244.jpg

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


心有法竹
浏览 77回答 2
2回答

MM们

根据描述,您需要变量“map”中提到的所有路径的可能组合。因此,您可以使用 itertools 来获取路径的所有可能组合。我想这应该对你有用:import itertoolspattern = 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 = [&nbsp; [1,2],&nbsp; [3,4,5],&nbsp; [6,7]]def possible_path(M,index,combination):&nbsp; &nbsp; for i in M[index]:&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if index<len(M)-1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; possible_path(M,index+1,combination+[i])&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python