简体   繁体   English

如何在有向图中检测循环中的循环

[英]How to detect cycle in a cycle in a Directed graph

I recently got a question in amazon interview and wanted to know stack overflow's views on the same . 我最近在亚马逊的采访中得到了一个问题,并想知道堆栈溢出的观点。

Question is that 问题是这样的

Input: A directed graph represented by adjacency list 输入:由邻接列表表示的有向图

Output required : does this graph have a cycle in a cycle and if yes what are those cycles . 需要输出:此图表是否在一个周期中有一个周期,如果是,那些周期是什么。 A cycle in a cycle condition is defined as follows : there are 2 cycles C1 and C2 in the graph & both of these share one or more edges then they will be called as cycles in a cycle . 循环条件中的循环定义如下:图中有2个循环C1和C2,这两个循环共享一个或多个边,然后它们将被称为循环中的循环。

Example bellow : 示例:
循环一个循环

In the above graph one can see there are 2 cylces C->D->E->F->G->H->C and another cycle represented as H->I->J->G->H .. We can see that these 2 cycles have the edges G->H as a shared edge and hence we can call these as cycles in a cycle . 在上图中,可以看到有2个圆柱C-> D-> E-> F-> G-> H-> C,另一个循环表示为H-> I-> J-> G-> H ..我们可以看到这两个周期具有边G-> H作为共享边,因此我们可以将它们称为循环中的循环。

So tha answer will be yes there are cycles in a cycles and
 the cyles are  C->D->E->F->G->H->C and H->I->J->G->H

My approach in an interview was to detect all cycles ( via DFS traversal ) and once detected maintain there edges in a hash map . 我在采访中的方法是检测所有周期(通过DFS遍历)并且一旦检测到在哈希映射中保持边缘。 Then when another cycle is found I again push them in hash . 然后当找到另一个循环时,我再次将它们推入哈希。 This was politely rejected and he moved further in the interview without discussing further . 这被礼貌地拒绝了,他在采访中进一步讨论,没有进一步讨论。 I then figured that finding all cycles is a hard problem . 然后我认为找到所有周期都是一个难题。 I am confused . 我很困惑 。 Can someone please clarify . 有人可以澄清一下。

  1. Find all cycles 找到所有周期
  2. Check for nonempty intersections between the edges of each pair of cycles (If the intersection is not empty the two cycles are a cycle in a cycle) 检查每对循环边缘之间的非空交点(如果交点不为空,则两个循环是一个循环中的循环)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM