2

I need to find circular dependency between classes and I immediately remember two things from the "Algorithms and Data Structures" course:

1)Finding a Loop in a Singly Linked List (Floyd’s Cycle-Finding Algorithm)

2)Depth-first search

So, I have a method that check circular dependency

 private void FindDependency(IDictionary<string, IEnumerable<string>> serviceDependence)

In input, we have a dictionary that contains, for example, <"A", < "B", "C" >> and <"B", < "A", "D" >>, this means that class A depends on class B and C. In the output, we have a circular dependency between A->B(in the more complex situation it will be a chain of dependency).

Which algorithms should I use and why?

Anatoly
  • 1,908
  • 4
  • 25
  • 47
  • 3
    building a dfs-tree of your dependency graph and finding back edges would work fine. – advocateofnone Apr 18 '15 at 11:17
  • this is a duplicate of http://stackoverflow.com/questions/29703972/in-c-how-to-find-chain-of-circular-dependency – Michael Sander Apr 18 '15 at 11:45
  • 3
    in case you don't want only to check for those cycles but also do a topological sort: those usually find cycles anyway (per failure) – Random Dev Apr 18 '15 at 11:46
  • If you don't want to use standard algorithms then try with linq: `var result = serviceDependence.Where(c => serviceDependence.Any(x => x.Value.Any(y => y == c.Key && c.Value.Any(z => z == x.Key)))).ToList();` – Giorgi Nakeuri Apr 18 '15 at 11:50
  • @GiorgiNakeuri What algorithms do you mean? And where I can find their implementations? – Anatoly Apr 18 '15 at 11:53
  • Haven't you just been provided with a link on your dublicate question with an answer? – Giorgi Nakeuri Apr 18 '15 at 12:01
  • @GiorgiNakeuri In my previous question we discuss my solution that work O(n^2). In this question, I'm trying to find the best way to solve this problem. – Anatoly Apr 18 '15 at 12:04
  • And difference between 1)Floyd’s Cycle-Finding Algorithm and 2) Depth-first search algorithms – Anatoly Apr 18 '15 at 12:05
  • 1
    Floyd's cycle-finding algorithm has the remarkable property of using only constant space, but it only works on *lists* -- it won't work on a general DAG. Depth-first search is the way to go here (or topological ordering, which is possibly something you will need to do anyway). – j_random_hacker Apr 18 '15 at 14:20

1 Answers1

3

If you can transform the dictionary in a graph you could do a topological sort on it. If there is a circular dependency the sorting will fail, else it will succeed.

Gentian Kasa
  • 776
  • 6
  • 10