Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Topological_Sort in python #55

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Algorithms/Pascal-Triangle.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> generate(int numRows) {
Expand Down
53 changes: 53 additions & 0 deletions Algorithms/Topological_Sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

from collections import defaultdict

# Graph Representation


class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices

# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)

# function for topologicalSort
def topologicalSortUtil(self, v, visited, stack):

# Mark the current node as visited.
visited[v] = True

# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i, visited, stack)

# Push current vertex to stack which stores result
stack.insert(0, v)


def topologicalSort(self):
# Mark all the vertices as not visited
visited = [False]*self.V
stack = []

for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i, visited, stack)

# Printing stack
print(stack)


g = Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)

print("Following is a Topological Sort of the given graph")
g.topologicalSort()