Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
srikars-1 authored Oct 20, 2021
1 parent 10e95c5 commit d02e6c2
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Topological-Sort/01_Topological_BFS.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include <bits/stdc++.h>
using namespace std;

void BFS(vector<int> adj[], int V, vector<int> &ans)
{
vector<int> indegree(V, 0);
for (int i = 0; i < V; i++)
{
for (auto z : adj[i])
{
indegree[z]++;
}
}

queue<int> q;
for (int i = 0; i < V; i++)
{
if (indegree[i] == 0)
{
q.push(i);
}
}

while (!q.empty())
{
int x = q.front();
q.pop();
ans.push_back(x);
for (auto z : adj[x])
{
indegree[z]--;
if (indegree[z] == 0)
{
q.push(z);
}
}
}
}

int main()
{
int V;
vector<int> adj[V];

vector<bool> visited(V, false);
vector<int> ans;

BFS(adj, V, ans);
return 0;
}
39 changes: 39 additions & 0 deletions Topological-Sort/02_Topological_DFS.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <bits/stdc++.h>
using namespace std;

void DFS(vector<int> adj[], vector<bool> &visited, stack<int> &st, int i)
{
visited[i] = true;
for (int x : adj[i])
{
if (!visited[x])
{
DFS(adj, visited, st, x);
}
}
st.push(i);
}

int main()
{
int V;
vector<int> adj[V];

vector<bool> visited(V, false);
vector<int> ans;
stack<int> st;
for (int i = 0; i < V; i++)
{
if (!visited[i])
{
DFS(adj, visited, st, i);
}
}

while (!st.empty())
{
ans.push_back(st.top());
st.pop();
}
return 0;
}

0 comments on commit d02e6c2

Please sign in to comment.