# requires python3.6 or above # requires networkx, matplotlib import numpy as np import networkx as nx import matplotlib as plt def all_cycles_k_recursive(G, source, k, current_node, visited, cycle, allcycles): """ """ # mark current node as visited visited[current_node] = True cycle.append(current_node) if k == 1: # maximum length achieved if G[current_node][source] == 1: print(cycle) allcycles.append(cycle[:]) else: for item in np.nonzero(G[current_node])[0]: if visited[item] == False: all_cycles_k_recursive(G, source, k-1, item, visited, cycle, allcycles) visited[current_node] = False cycle.pop() # make the current node available def all_cycles_k(G, source, k): """ G: numpy adj array with element i,j == 1 if there's a connection from i to j (transpose of the conventional adj mat) source: source node, int number k: length of the cycles, int number """ allcycles = [] visited = [False] * np.max(G.shape) cycle = [] # current cycle #cycle.append(source) all_cycles_k_recursive(G, source, k-1, source, visited, cycle, allcycles) return allcycles