In the below code, while trying to print all cycles, there comes the case where multiple cycles exist for one node. Even though I am increasing the value of k in the cycle function, it doesn't print all the possible cycles for a given node i.e. it doesn't consider the two possible cycles for node 3 or index 2 to index 1 as well as index 3 of the node 1 or index 0. Here we discuss the following graph, represented as mat in the code. Example Image
output the code prints:
['1 -> 2', '2 -> 3', '3 -> 1']
['1 -> 4', '4 -> 5', '5 -> 1']
['2 -> 3', '3 -> 1', '1 -> 2']
['3 -> 1', '1 -> 2', '2 -> 3']
Where the code fails is on the path [ [3 -> 1 ] , [1 -> 4] , [4-> 5] , [5-> 1] , [1 -> 2] , [2-> 3]]. With this code, I aim to print all cycles for a given adjacency matrix, even considering the case where no cycles exist.
I expect the output for the given an example as:
['1 -> 2', '2 -> 3', '3 -> 1']
['1 -> 4', '4 -> 5', '5 -> 1']
['2 -> 3', '3 -> 1', '1 -> 2']
['3 -> 1', '1 -> 2', '2 -> 3']
['2 -> 3', '3 -> 1', '1 -> 4', '4 -> 5', '5 -> 1', '1 -> 2']
['3 -> 1', '1 -> 4', '4 -> 5', '5 -> 1', '1 -> 2', '2 -> 3']
['4 -> 5', '5 -> 1', '1 -> 2', '2 -> 3', '3 -> 1', '1 -> 4']
['5 -> 1', '1 -> 2', '2 -> 3', '3 -> 1', '1 -> 4', '4 -> 5']
Code Sample:
mat = [[0,1,0,1,0] , [0,0,1,0,0] , [1,0,0,0,0] , [0,0,0,0,1] , [1,0,0,0,0]]
def cycle(mat,i,j,find):
global temp,t
k = 0
while k != len(mat):
if k != j and mat[j][k] and (temp == [] or temp[-1][-1] == str(j+1)):
temp.append(f'{j+1} -> {k+1}')
if k == find:
print(temp)
return 1
else:
t.append([i,j,k,find])
if t.count([i,j,k,find]) > 1:
return -1
cycle(mat,j,k,find)
k = k+1
for i in range(len(mat)):
for j in range(len(mat)):
if mat[i][j] and i != j:
temp = []
t = []
temp.append(f'{i+1} -> {j+1}')
cycle(mat,i,j,i)
Logic:
We are trying to go from : i -> j to : j -> k (where i , j , k are nodes) using cycle function. I've used
(temp == [] or temp[-1][-1] == str(j+1))
to make sure that after i -> j , only j -> k gets appended
t.append([i,j,k,find])
if t.count([i,j,k,find]) > 1:
return -1
conditions to prevent it from going into infinite recursion. For Detailed Logic click.
Thank you for your time and for helping me with my first StackOverflow question.