C++ program to check whether it is possible to finish all the tasks or not from given dependencies

In this article, we will be discussing a program to check if it is possible to finish all the given tasks on the basis of the given prerequisites.

For example, let us say we have been given three tasks and prerequisites are [[1, 0], [2, 1], [3, 2]].

( [1,0] means that to pick up ‘1’ task; the ‘0’ task must be completed first.)

Then, in this example since the ‘0’ task doesn’t have any prerequisite it can be completed first. Then the ‘1’ task can be completed, since the ‘0’ task has been completed. Similarly, both ‘2’ and ‘3’ tasks can also be completed. So the answer in this case will be “True”.

This problem can be solved using graph algorithms. Since, arrays aren’t convenient with graph algorithms, we will convert it into a graph. This can be done by making an edge from say a task ‘m’ to task ‘n’, if task ‘n’ is having dependency as completion of ‘m’.

Once the graph is made we can use DFS. In that, we can start from a particular node and then visit its nearest node and then the nearest node to that node and so on. If we encounter a node that has been previously visited, a cycle is made and we will return “False”. Otherwise, once we reach a terminal, this pattern will again be followed by another node till all the nodes in the graph has been visited. If all the nodes has been reached, we will return “True”.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
// Converts list into graph
vector<unordered_set<int> > make_graph(int Tasks, vector<pair<int, int> >& dependencies) {
   vector<unordered_set<int> > graph(Tasks);
   for (auto pre : dependencies)
   return graph;
//to check if all the nodes are visited
bool cycle(vector<unordered_set<int> >& graph, int node, vector<bool>& onway, vector<bool>& visited) {
   if (visited[node])
      return false;
   onway[node] = visited[node] = true;
   for (int near : graph[node]) {
      if (onway[near] || cycle(graph, near, onway, visited))
         return true;
   return onway[node] = false;
//to check if all the tasks can be completed
bool canFinish(int Tasks, vector<pair<int, int> >& dependencies) {
   vector<unordered_set<int>>graph = make_graph(Tasks, dependencies);
   vector<bool> onway(Tasks, false), visited(Tasks, false);
   for (int i = 0; i < Tasks; i++) {
      if (!visited[i] && cycle(graph, i, onway, visited))
         return false;
   return true;
int main() {
   int Tasks = 6;
   vector<pair<int, int >> dependencies;
   dependencies.push_back(make_pair(1, 0));
   dependencies.push_back(make_pair(2, 1));
   dependencies.push_back(make_pair(3, 2));
   dependencies.push_back(make_pair(5, 3));
   dependencies.push_back(make_pair(4, 5));
   if (canFinish(Tasks, dependencies)) {
      cout << "True";
   else {
      cout << "False";
   return 0;