-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_cycles.py
101 lines (68 loc) · 2.2 KB
/
count_cycles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#Andrew Dhawan
#Sept 8 2016
#count_cycles.py
#This code enables the count of unique cycles of a particular length
#implements a DFS on an adjacency matrix for a weighted graph.
#Element (i,j)=1 of the adjacency matrix indicates a directed edge
#from node j to node i.
import numpy as np
def find_path_to_vertex (graph, cur_vert, dest_vert, itera, start, cur_traj):
global count
if (itera==0 and cur_vert==dest_vert):
count +=1
# print("Cycle found: " + str(dest_vert)+ cur_traj + str(cur_vert))
return 0
if (itera==0):
return 0
if (cur_vert == dest_vert and start==0):
return 0
if (start==0):
cur_traj += str(cur_vert)
for i in range(len(graph[:,cur_vert])):
if (graph[i,cur_vert] ==1 and itera>0):
if (cur_traj.find(str(i))<0):
find_path_to_vertex(graph, i, dest_vert, itera-1,0,cur_traj)
return 0
#adjacency matrix for the graph:
#G = np.array([[0,0,0,1],[0,0,0,1],[1,1,0,1],[0,1,0,0]])
G = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0, 1, 1],[0, 0, 0, 0, 0, 1, 1, 1, 1, 0],[0, 0, 0, 0 ,0, 0, 1, 0, 1, 1],[0, 0, 0, 0, 0 ,0, 1, 0, 0, 0],[0, 0, 0, 0, 0, 1, 0, 0, 0, 1],[0, 0, 0 ,0 ,1 ,1, 1, 0, 1, 0],[1, 0 ,0, 1 ,0, 1, 1, 1, 0, 0],[1, 1, 1, 1, 0, 1, 1, 0, 1, 0]])
#find all cycles of length 2
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 2,1,"")
print(count/2)
#find all cycles of length 3
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 3,1,"")
print(count/3)
#find all cycles of length 4
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 4,1,"")
print(count/4)
#find all cycles of length 5
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 5,1,"")
print(count/5)
#find all cycles of length 6
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 6,1,"")
print(count/6)
#find all cycles of length 7
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 7,1,"")
print(count/7)
#find all cycles of length 8
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 8,1,"")
print(count/8)
#find all cycles of length 9
count = 0
for i in range(len(G[:,1])):
find_path_to_vertex(G, i, i, 9,1,"")
print(count/9)