Find all chordless cycles in an undirected graph

前端 未结 5 1369
有刺的猬
有刺的猬 2020-12-04 15:47

How to find all chordless cycles in an undirected graph?

For example, given the graph

0 --- 1
|     | \\
|     |  \\
4 --- 3 - 2

th

5条回答
  •  情书的邮戳
    2020-12-04 16:18

    Assign numbers to nodes from 1 to n.

    1. Pick the node number 1. Call it 'A'.

    2. Enumerate pairs of links coming out of 'A'.

    3. Pick one. Let's call the adjacent nodes 'B' and 'C' with B less than C.

    4. If B and C are connected, then output the cycle ABC, return to step 3 and pick a different pair.

    5. If B and C are not connected:

      • Enumerate all nodes connected to B. Suppose it's connected to D, E, and F. Create a list of vectors CABD, CABE, CABF. For each of these:
      • if the last node is connected to any internal node except C and B, discard the vector
      • if the last node is connected to C, output and discard
      • if it's not connected to either, create a new list of vectors, appending all nodes to which the last node is connected.

      Repeat until you run out of vectors.

    6. Repeat steps 3-5 with all pairs.

    7. Remove node 1 and all links that lead to it. Pick the next node and go back to step 2.

    Edit: and you can do away with one nested loop.

    This seems to work at the first sight, there may be bugs, but you should get the idea:

    void chordless_cycles(int* adjacency, int dim)
    {
        for(int i=0; i > candidates;
                for(int k=j+1; k v;
                    v.resize(3);
                    v[0]=j;
                    v[1]=i;
                    v[2]=k;
                    candidates.push_back(v);
                }
                while(!candidates.empty())
                {
                    vector v = candidates.front();
                    candidates.pop_front();
                    int k = v.back();
                    for(int m=i+1; m w = v;
                        w.push_back(m);
                        candidates.push_back(w);
                    }
                }
            }
        }
    }
    

提交回复
热议问题