题目解析:有向边,不含环路,起点不确定
深度首先算法:每条路径先搜索至最深,回头处理分叉路径,将路径转化为邻接矩阵如下图
先搜索出来离起点最近的,最深的路径,然后依次倒退路径,搜索出来其他分叉的路径,如下:
如以零点为起点,首先检索到了(0,1)点,然后检索到(1,2),在检索到(2,3),然后倒退到第二行,,第二行无第二路径,再倒退到第一行,无重复路径,最后倒退到第0行,发现重复路径。整个过程一直在循环。
输入上先是节点,后是有向边
4
0 1
1 2
2 3
0 2
代码如下:
node = int(input()) #节点数
in_list = []#命名输入矩阵
#输入矩阵
while 1:
try:#不确定多少个有向边
a,b = input().split()
in_list.append([int(a),int(b)])
except:
break
#转化为邻接矩阵
list1 = [[0] * node for _ in range(node)]
for i in in_list: list1[i[0]][i[1]] = 1
#获取路径数量
def get_path(zero_node,nodes,in_list):
next_node,number = -1,0
queue = [[zero_node,next_node]]
while queue:
find = 0
while find == 0 and next_node < nodes-1:
next_node += 1
if in_list[queue[-1][0]][next_node] == 1:
queue[-1][1] = next_node
number += 1
find = 1
if find == 1:
queue.append([next_node,0])
next_node = -1
else:
queue.pop()
if queue:
next_node = queue[-1][1]
return number
def main():
maxpath, I = -1, 0 # 获取最大路径数, 和选择的位置
for i in range(node): # 每个结点获取一次最大路径数
tmppath = get_path(i, node, list1)
print(tmppath)
if tmppath > maxpath:
maxpath, I = tmppath, i
print('最大路径起始点:',I,'最大路径数:', maxpath)
if __name__ == '__main__':
main()