What would be a good algorithm for a circular reference check in this case?

前端 未结 2 1549
旧巷少年郎
旧巷少年郎 2021-02-19 03:12

Given you have the following class (bad C#, but you get the drift):

public abstract class AmICircular
{
  // assume Children is never null
  private List

        
2条回答
  •  忘了有多久
    2021-02-19 03:18

    The iterative solution is to define a set R (reachable) and CR (children of Reachable).

    You start of with R = {this} and CR = {this.children}.

    In each step, you check if CR contains this (or target, depending on your exact goal). If not, you add CR to R and set CR to the children of CR, and remove the elements of R from CR.

    If CR becomes empty, R is the complete set of elements reachable from this.

提交回复
热议问题