Ask Your Question
0

Determine whether a vertex lies on a cycle of given length

asked 2025-04-20 17:20:52 +0200

licheng gravatar image

updated 2025-04-20 17:21:14 +0200

Given a graph G and a vertex u of G, the problem of determining whether there exists a cycle of length k starting at u is a common one in graph theory.

Mathematica provides a function Findcycle ( FindCycle[{g, v}, …] finds a cycle that contains the vertex v.) for this task, though I am not sure which algorithm it employs—perhaps depth-first search (DFS)? Sage, on the other hand, does not appear to have a corresponding built-in function.

2 Answers

Sort by » oldest newest most voted
1

answered 2025-04-27 17:32:46 +0200

updated 2025-04-27 17:34:09 +0200

You can also use method all_simple_paths, and there si no need for removing v from the graph

def FindCycle(G, v, cycle_len):
    for cycle in G.all_simple_paths(starting_vertices=[v], ending_vertices=[v], max_length=cycle_len):
        if len(cycle) == cycle_len + 1:
            return cycle
    return None

For instance

sage: FindCycle(graphs.CompleteGraph(4), 0, 3)
[0, 1, 2, 0]

It remains to deal with the special cases cycle_len == 1 which can happen if the graph has loops and the case cycle_len == 2 for which the proposed method returns a non simple cycle (e.g., [0, 1, 0]),

link
1

answered 2025-04-21 15:57:49 +0200

Max Alekseyev gravatar image

Removing a given vertex v and searching for a simple path connecting two vertices from the neighborhood of v should do the job:

def FindCycle(G, v, cycle_len):
    H = G.copy()
    H.delete_vertex(v)
    try:
        return [v] + next(p for p in H.all_paths_iterator(starting_vertices=G.neighbors(v), ending_vertices=G.neighbors(v), simple=True, max_length=cycle_len-2) if len(p)==cycle_len-1)
    except StopIteration:
        return None

For example, FindCycle(graphs.CompleteGraph(4), 0, 3) produces the cycle (as a list of vertices) [0, 3, 1].

link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2025-04-20 17:20:52 +0200

Seen: 175 times

Last updated: Apr 27