欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 图论入门编程

图论入门编程

2024/11/29 17:41:44 来源:https://blog.csdn.net/qq_38742161/article/details/144066212  浏览:    关键词:图论入门编程

卡码网刷题链接:98. 所有可达路径

一、题目简述

二、编程demo

方法①邻接矩阵

from collections import defaultdict
#简历邻接矩阵
def build_graph(): n, m = map(int,input().split()) graph = [[0 for _ in range(n+1)] for _ in range(n+1)]for _ in range(m): i,j = map(int,input().split()) graph[i][j] = 1return graph,n
#深度优先搜索
def dfs(g,r,i,end,path):if i == end:r.append(path.copy())return for k in range(1,end+1):if g[i][k]:path.append(k)dfs(g,r,k,end,path)path.pop()return 
#主函数
def main():graph,n = build_graph()result = []path = [1]dfs(graph,result,1,n,path)#按格式打印输出if not result:print(-1)for p in result:print(" ".join(map(str,p)))return 
if __name__ == "__main__":main()

方法②邻接表

from collections import defaultdict
def build_graph(): n, m = map(int,input().split()) graph = defaultdict(list) for _ in range(m): i,j = map(int,input().split()) graph[i].append(j)return graph,ndef dfs(g,r,i,end,path):if i == end:r.append(path.copy())return for k in g[i]:path.append(k)dfs(g,r,k,end,path)path.pop()return def main():graph,n = build_graph()result = []path = [1]dfs(graph,result,1,n,path)if not result:print(-1)for p in result:print(" ".join(map(str,p)))return 
if __name__ == "__main__":main()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com