This problem is related to Topological Sorting.
Think about every job as a node of a graph. The rest of the approach is same as top sort.
Procedure to solve the problem:
Initially, in-degree of every node is 0.
Now change the in-degree of all nodes based on the given job relations.
Now run DFS or BFS from nodes whose in-degree is 0. Rest of the procedure is same as Topological Sorting.
Let's consider your given input.
1 -> 2
1 -> 5
2 -> 3
4 -> 2
4 -> 5
5 -> 6
inDegree[1] = 0
inDegree[2] = 2 (1->2, 4->2
)
inDegree[3] = 1 (2->3
)
inDegree[4] = 0
inDegree[5] = 2 (1->2, 4->5
)
inDegree[6] = 1 (5->6
)
If we run DFS from node 1 first, mark it's corresponding nodes as done
then, 1, 2, 3
nodes will be processed. As relation between these
nodes (1->2->3
).
Note: Here it processed nodes could be 1, 5, 6
based on the relation 1->5->6
. It'll also give the right answer.
Which nodes will be processed first, it depends on the way you make the adjacency list.
Then 4
will be left as the unprocessed node whose in-degree is 0. So
if we run DFS from 4
, then 4, 5, 6
will be processd. As relation
between these nodes (4->5->6
).
So you've your answer, which is 2
.
Note: After processing a path, new node can be found which is left unprocessed and whose in-degree is 0.
For example, consider the relation 1->2, 2->3
, 2->4
.
If you first process the path 1->2->3
, 4
will be left unprocessed.
If you first process the path 1->2->4
, 3
will be left unprocessed.
Just following the basic Topological Sorting procedure will give you the answer.
You'll have to count, from how many unprocessed nodes with in-degree 0, you're running the DFS.
Helpful resources to learn about topological sorting: