I want to count the number of four-cycles and the number of six-cycles in a bipartite igraph in R. Adapting the code in r igraph find all cycles, I've come up with this solution:
> set.seed(1)
> library(igraph)
> G <- bipartite.random.game(10,10,p=.5) #A random bipartite
>
> cycles <- NULL #List all cycles up to length 6 (2-cycles, 4-cycles, and 6-cycles)
> for(v1 in V(G)) {for(v2 in neighbors(G, v1)) {cycles <- c(cycles, lapply(all_simple_paths(G, v2, v1, cutoff = 5), function(p) c(v1,p)))}}
> fourcycles <- cycles[which(sapply(cycles, length) == 5)] #Just four-cycles
> fourcycles <- fourcycles[sapply(fourcycles, min) == sapply(fourcycles, `[`, 1)] #Unique four-cycles
> length(fourcycles) #Number of four-cycles
[1] 406
>
> sixcycles <- cycles[which(sapply(cycles, length) == 7)] #Just six-cycles
> sixcycles <- sixcycles[sapply(sixcycles, min) == sapply(sixcycles, `[`, 1)] #Unique six-cycles
> length(sixcycles) #Number of six-cycles
[1] 5490
It works, but is impractical for even slightly larger graphs because there are potentially exponentially many cycles to enumerate. Is there a way to do this more efficiently, maybe exploiting the fact that the graph is bipartite? Thanks!