Haris
Haris

Reputation: 721

Which graph traversal algo suits in this scenario

I have a problem to traverse a graph of the following kind.

Graph to traverse

This traversal comes to mind:

So what traversal algo you think would work best in this scenario. BFS would probably not work because in my case I do not know all the inputs when I reach a node and backtracking is not possible.

I have to implement this in C#.

Upvotes: 1

Views: 95

Answers (1)

Bernhard Barker
Bernhard Barker

Reputation: 55639

Idea:

Use breadth-first search, but also have a count on each node (or, similarly, a list of the inputs).

When you visit a node:

  • Increase its count
  • If the count is less than the number of incoming edges it has, don't do anything
  • Otherwise, process the node as usual

Your example:

Candidates: A
We process A.

Candidates: C, B, D
We visit C, but don't process it as its count = 1 < 2 = incoming edges.

Candidates: B, D
We visit B and process it.

Candidates: D, C, E, D
We visit D, but don't process it as its count = 1 < 2 = incoming edges (the second edge hasn't been processed yet).

Candidates: C, E, D
We visit C and process it.

Candidates: E, D, E
We visit E, but don't process it as its count = 1 < 3 = incoming edges (the second and third edges haven't been processed yet).

Candidates: D, E
We visit D and process it.

Candidates: D, E, E
We visit D and process it.

Candidates: E, E
We visit E, but don't process it as its count = 2 < 3 = incoming edges (the third edge hasn't been processed yet).

Candidates: E
We visit E and process it.

Upvotes: 4

Related Questions