How to find a triangle inside a graph?

前端 未结 4 758
刺人心
刺人心 2021-01-31 18:05

Here is an exercise in the Algorithm Design Manual.

Consider the problem of determining whether a given undirected graph G = (V, E) contains a triangle

4条回答
  •  星月不相逢
    2021-01-31 18:35

    A possible O(|V||E|) solution, is the same idea of the brute-force in (a):

    for each edge (u, v):
      for each vertex w:
         if (v, w) is an edge and (w, u) is an edge:
              return true
    return false
    

    check all edges, and not all vertices pairs - with another vertex that forms a triangle - it is enough information to determine if the edge and vertex form a feasible solution.

    Counter example to BFS solution:

           A
         / | \
        /  |  \
       B   C   D
       |   |   |
       |   |   |
       F---G---H
       |       |
       ---------
        (F, H) is also an edge
    

    Note that father[F] != father[G] != father[H], thus the algorithm will return false - but nevertheless, (F, G, H) is a feasible solution!

提交回复
热议问题