master 6a539c279308 cached
46 files
78.7 KB
24.3k tokens
80 symbols
1 requests
Download .txt
Repository: MUSoC/Visualization-of-popular-algorithms-in-Python
Branch: master
Commit: 6a539c279308
Files: 46
Total size: 78.7 KB

Directory structure:
gitextract_rqk1_unp/

├── A_star_search/
│   ├── README.md
│   ├── a_star_search.py
│   ├── heuristics.txt
│   └── input.txt
├── Assignment Problem/
│   ├── README.md
│   ├── assignment_prob_hungarian.py
│   └── input.txt
├── BFS/
│   ├── README.md
│   ├── bfs.py
│   └── input.txt
├── BellmanFord/
│   ├── BellmanFord.py
│   └── input.txt
├── DFS/
│   ├── README.md
│   ├── dfs_visual.py
│   └── input.txt
├── Dijsktra's/
│   ├── README.md
│   ├── dijsktras.py
│   └── input.txt
├── Egocentric Network/
│   ├── egocentric_network_1.py
│   ├── egocentric_network_1_5.py
│   ├── egocentric_network_2.py
│   └── input.txt
├── Graph Coloring/
│   ├── README.md
│   ├── graph_coloring.py
│   └── input.txt
├── Greedy BFS/
│   ├── README.md
│   ├── greedy_bfs.py
│   ├── heuristics.txt
│   └── input.txt
├── K Centers Problem/
│   ├── README.md
│   ├── input.txt
│   └── k_centers_problem.py
├── Kruskal's/
│   ├── README.md
│   ├── input.txt
│   └── kruskals_quick_union.py
├── Prim's/
│   ├── README.md
│   ├── input.txt
│   └── prims.py
├── README.md
├── Topological Sort/
│   ├── README.md
│   ├── input.txt
│   └── topological_sort.py
├── Travelling Salesman Problem/
│   ├── README.md
│   ├── input.txt
│   └── tsp_christofides.py
└── setup.sh

================================================
FILE CONTENTS
================================================

================================================
FILE: A_star_search/README.md
================================================
# Visualisation of A* Search using networkx library

### A* Search ###

A* search( pronounced as "A star") is a search algorithm which explores a graph by expanding the that node which minimizes steps from the source(like in BFS) as well as approximate steps to the goal(like in greedy bfs). Hence, this algorithm is thorough and fast as it combines the strengths of both BFS and Greedy BFS.
A* algorithm is proven to give the optimal solution to a problem.

What is the evaluation function here?

Evaluation function-f is the criterion based on which the next node is chosen. 
f is the sum of 2 parameters:
1. cost of path from source to the given node
2. approximate cost of reaching the goal from the given node (heuristic function)
So, at each step, the node is chosen such that sum of the above 2 parameters, that is, f is minimal. 

### Algorithm

Starting from source city, we choose the next city such that it is in the shortest path from the source (based on the cost of the route from source) as well as the closest to the Goal city(based on the heuristics function) amongst all it's neighbours. We terminate, once we've reached the goal city.



Let us understand this better through an example.

![Romania map](https://user-images.githubusercontent.com/22571531/27821959-ac69755a-60c1-11e7-8286-951cd1c0437f.png)

Source: Artificial Intelligence A Modern Approach
        by Stuart J. Russell and Peter Norvig 

Given here is the map of Romania with cities and distance between them. We need to find the shortest route from Arad to Bucharest. 

The heurestics that we are using here is the straight-line distance from the city to the goal(Here, Bucharest). Note that, this straight line distance is obtained only by knowing the map coordinates of the 2 cities. 


#### Input

Input is taken from the file 
```
input.txt
```

Each line in the input is of the form 
```
city1 city2 dist
```
It denotes each element of the adjacency list. That is, dist is the distance between city1 and city2. An undireced graph is drawn depicting the map of Romania.
Starting city: Arad
Goal city: Bucharest

Heuristics is loaded from the file
```
heuristics.txt
```
Each line is of the form
```
city h
```
'h' stands for the heuristics value(here, the straight line distnace) from the city 'city' to goal city(here, Bucharest)

#### Working: 


Here, Arad is the starting city. The first node to be expanded from Arad will be Sibiu, because it has a smaller value of f (140+253=393) than either Zerind (75+374=449_)or Timisoara(118 + 329 =447). The next node to be expanded will be Rimnicu_Vilcia, because it has a smaller f compared to other possible nodes. Similary, Pitesti is expanded next and finally Bucharest is reached.

Here, is the resultant graph.                                              
Green coloured node denotes the starting city(Here, Arad).                                             
Red coloured node denotes the goal city(Here, Bucharest).                                                           
Edges marked with black is the route from Arad to Bucharest generated by the A* search algorithm.
![final-route](https://user-images.githubusercontent.com/22571531/27867257-c85c0e94-61b6-11e7-8b08-c2b1972e67b3.png)

#### Complexity ####

Time: O(b^d)                                                                
b - Branching factor, the average number of successors per state        
d - depth of the shortest path                        

================================================
FILE: A_star_search/a_star_search.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import Queue as Q
 
 

def getPriorityQueue(G, v):
	q = Q.PriorityQueue()
	for node in G[v]:
		q.put(Ordered_Node(float(heuristics[node])+float(G[node][v]['length']),node))
	return q,len(G[v])



def aStarSearchUtil(G, v, visited, final_path, dest, goal): 
	if goal == 1:
		return goal
	visited[v] = True
	final_path.append(v)
	if v == dest:
		goal = 1
	else:
		pq_list = []
		pq,size = getPriorityQueue(G, v)
		for i in range(size):
			pq_list.append(pq.get().description)
		for i in pq_list:
			if goal != 1:
				#print "current city:", i
				if visited[i] == False :
					goal = aStarSearchUtil(G, i, visited, final_path, dest, goal)
	return goal


 
def aStarSearch(G, source, dest, heuristics, pos): 
	visited = {}
	for node in G.nodes():
		visited[node] = False
	final_path = []
	goal = aStarSearchUtil(G, source, visited, final_path, dest, 0)
	prev = -1
	for var in final_path:
		if prev != -1:
			curr = var
			nx.draw_networkx_edges(G, pos, edgelist = [(prev,curr)], width = 2.5, alpha = 0.8, edge_color = 'black')
			prev = curr
		else:
			prev = var
	return



class Ordered_Node(object):
	def __init__(self, priority, description):
		self.priority = priority
		self.description = description
		return
	def __cmp__(self, other):
		return cmp(self.priority, other.priority)

def getHeuristics(G):
	heuristics = {}
	f = open('heuristics.txt')
	for i in G.nodes():
		node_heuristic_val = f.readline().split()
		heuristics[node_heuristic_val[0]] = node_heuristic_val[1]
	return heuristics



#takes input from the file and creates a weighted graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	for i in range(n):
		graph_edge_list = f.readline().split()
		G.add_edge(graph_edge_list[0], graph_edge_list[1], length = graph_edge_list[2]) 
	source, dest= f.read().splitlines()
	return G, source, dest



def DrawPath(G, source, dest):
	pos = nx.spring_layout(G)
	val_map = {}
	val_map[source] = 'green'
	val_map[dest] = 'red'
	values = [val_map.get(node, 'blue') for node in G.nodes()]
	nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'b' ,width = 1, alpha = 0.7)  #with_labels=true is to show the node number in the output graph
	edge_labels = dict([((u, v,), d['length']) for u, v, d in G.edges(data = True)])
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.5, font_size = 11) #prints weight on all the edges
	return pos



#main function
if __name__ == "__main__":
	G, source,dest = CreateGraph()
	heuristics = getHeuristics(G)
	pos = DrawPath(G, source, dest)
	aStarSearch(G, source, dest, heuristics, pos)
	plt.show()






================================================
FILE: A_star_search/heuristics.txt
================================================
Arad 366
Bucharest 0
Craiova 160
Dobreta 242
Eforie 161
Fagaras 178
Giurgiu 77
Hirsova 151
Iasi 226
Lugoj 244
Mehadia 241
Neamt 234
Oradea 380
Pitesti 98
Rimnicu_Vilcea 193
Sibiu 253
Timisoara 329
Urziceni 80
Vaslui 199
Zerind 374

================================================
FILE: A_star_search/input.txt
================================================
23
Arad Sibiu 140
Arad Timisoara 118
Arad Zerind 75
Bucharest Fagaras 211
Bucharest Giurgiu 90
Bucharest Pitesti 101
Bucharest Urziceni 85
Craiova Dobreta 120
Craiova Pitesti 138
Craiova Rimnicu_Vilcea 146
Dobreta Mehadia 75
Eforie Hirsova 86
Fagaras Sibiu 99
Hirsova Urziceni 98
Iasi Neamt 87
Iasi Vaslui 92
Lugoj Mehadia 70
Lugoj Timisoara 111
Oradea Zerind 71
Oradea Sibiu 151
Pitesti Rimnicu_Vilcea 97
Rimnicu_Vilcea Sibiu 80
Urziceni Vaslui 142
Arad
Bucharest

================================================
FILE: Assignment Problem/README.md
================================================
# Visualisation of Assignment Problem using networkx library

### INPUT ###


Input is taken from the file 
#### input.txt ####

Sample input
```
 4
 9 2 7 8
 6 4 3 7 
 5 8 1 8
 7 6 9 4

```
First line contains n, the number of people which is the same as the number of jobs.
Followed by n*n weighted profit matrix.


### Draw Graph ###


A bipartite graph is to be drawn. Person and Job - are the 2 sets of nodes. Since, person is connected to every possible job and a job has connection from every person.

![1](https://user-images.githubusercontent.com/22571531/27514223-5fa03ec4-59a1-11e7-9bdc-8d9c17afc030.png)


### Assignment Problem ###

Assignment Problem is a combinatorial optimization problem. It consists of finding a maximum weight matching (or minimum weight perfect matching) in a weighted bipartite graph.

Here, we have n people and n jobs that need to be done. Given profit matrix, we need to assign exactly one person to each job and exactly one job to each person in such a way that the total profit of the assignment in maximized.
(It is a linear assignment problem, since number of people and jobs are equal.)

Hungarian algorithm is one of the most effient methods that solves the linear assignment problem in polynomial time(with a time complexity of O(n^3)).

The code here,is an implementation of Hungarian algorithm. 
The resultant graph for the sample input with maximum weight matching (denoted by red edges):

![2](https://user-images.githubusercontent.com/22571531/27514224-645f8028-59a1-11e7-92b0-5f0d7f0b8b02.png)

#### Complexity ####

Time: O(n^3)                                                          
n - number of people( = number of jobs)


================================================
FILE: Assignment Problem/assignment_prob_hungarian.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import bipartite
from string import ascii_lowercase



def init_labels(cost):
	n = len(cost)
	lx = [0] * n
	ly = [0] * n
 	for x in range(n):
 		for y in range(n):
 			lx[x] = max(lx[x], cost[x][y])
 	return lx,ly



def update_labels(T, slack, S, lx, ly, n):
	delta = float("inf");
	for y in range(n):
		if T[y] == 0:
			delta = min(delta, slack[y])
 	for x in range(n):
		if S[x] != 0:
			lx[x] -= delta
 	for y in range(n):
		if T[y] != 0:
			ly[y] += delta
 	for y in range(n):
 		if T[y] == 0:
			slack[y] -= delta



def add_to_tree(x, prevx, S, prev, lx, ly, slack, slackx, cost):
	n = len(cost)
	S[x] = True
 	prev[x] = prevx
 	for y in range(n):
 		if (lx[x] + ly[y] - cost[x][y]) < slack[y]:
 			slack[y] = lx[x] + ly[y] - cost[x][y]
 			slackx[y] = x
 


def augment(cost, max_match, xy, yx, lx, ly, slack, slackx):
	n = len(cost)
	if max_match == n:
		return;
 	q = [0] * n
	wr = 0
	rd = 0
	root = 0
	S = [False] * n
	T = [False] * n
	prev = [-1] * n 
	for x in range(n):
		if xy[x] == -1:
			q[wr] = x
			wr = wr+1
			root = x
 			prev[x] = -2
 			S[x] = True
 			break
 	for y in range(n): 
 		slack[y] = lx[root] + ly[y] - cost[root][y]
 		slackx[y] = root
  	while True:
 		while rd < wr:
 			x = q[rd]
 			rd = rd+1
 			for y in range(n):
 				if (cost[x][y] == lx[x] + ly[y] and T[y] == 0):
					if yx[y] == -1:
						break
 					T[y] = True
 					q[wr] = yx[y]
 					wr = wr+1
 					add_to_tree(yx[y], x, S, prev, lx, ly, slack, slackx, cost)
 			if y < n:
 				break
		if y < n:
			break
		update_labels(T, slack, S, lx, ly, n)
		wr = 0 
		rd = 0
 		for y in range(n):
			if T[y] == 0 and slack[y] == 0:
				if yx[y] == -1:
					x = slackx[y]
 					break
 				else:
					T[y] = true
 					if S[yx[y]] == 0:
 						q[wr] = yx[y]
 						wr = wr+1
 						add_to_tree(yx[y], slackx[y], S, prev, lx, ly, slack, slackx, cost)
 		if y < n:
			break
	if y < n:
		max_match = max_match+1
		cx = x
		cy = y
		ty = 0
		flag = 0
		if cx != -2:
			ty = xy[cx];
 			yx[cy] = cx;
 			xy[cx] = cy;
 			cx = prev[cx]
			cy = ty
		while cx != -2:
			ty = xy[cx]
 			yx[cy] = cx
			xy[cx] = cy
			cx = prev[cx]
			cy = ty
 		augment(cost, max_match, xy, yx, lx, ly, slack, slackx)



def hungarian(B ,pos ,cost):
	n = len(cost)
	ret = 0; 
	max_match = 0 
	xy = [-1] * n
	yx = [-1] * n
	slack = [0] * n
	slackx = [0] * n
	lx, ly = init_labels(cost)
	augment(cost, max_match, xy, yx, lx, ly, slack, slackx)
	for x in range(n):
 		if (x, chr(xy[x]+97)) in B.edges():
			nx.draw_networkx_edges(B, pos, edgelist = [(x, chr(xy[x]+97))], width = 2.5, alpha = 0.6, edge_color = 'r')



#takes input from the file and creates a weighted bipartite graph
def CreateGraph():
	B = nx.DiGraph();
	f = open('input.txt')
	n = int(f.readline())
	cost = []
	
	for i in range(n):
		list1 = map(int, (f.readline()).split())
		cost.append(list1)
	people = []
	for i in range(n):
		people.append(i)
	job = [] 
	for c in ascii_lowercase[:n]:
		job.append(c)
	B.add_nodes_from(people, bipartite=0) # Add the node attribute "bipartite"
	B.add_nodes_from(job, bipartite=1)
	for i in range(n) :
		for c in ascii_lowercase[:n] :
			if cost[i][ord(c)-97] > 0 :
				B.add_edge(i, c, length = cost[i][ord(c)-97])  
	return B,cost



def DrawGraph(B):
	l, r = nx.bipartite.sets(B)
	pos = {}
	# Update position for node from each group
	pos.update((node, (1, index)) for index, node in enumerate(l))
	pos.update((node, (2, index)) for index, node in enumerate(r))
	nx.draw(B, pos, with_labels = True)  #with_labels=true is to show the node number in the output graph
	edge_labels = dict([((u, v), d['length']) for u, v, d in B.edges(data = True)])
	nx.draw_networkx_edge_labels(B, pos, edge_labels = edge_labels, label_pos = 0.2, font_size = 11) #prints weight on all the edges
	return pos



#main function
if __name__ == "__main__":
	B, cost = CreateGraph();
	pos = DrawGraph(B)
	hungarian(B, pos, cost)
	plt.show()
	

================================================
FILE: Assignment Problem/input.txt
================================================
4
9 2 7 8
6 4 3 7 
5 8 1 8
7 6 9 4

================================================
FILE: BFS/README.md
================================================
# Visualisation of BFS traversal using networkx library

### INPUT ###


Input is taken from the file 
#### input.txt ####

Sample input
```
4
0 5 10 5
0 0 5 0
0 10 0 0
0 0 10 0
0


```
First line contains the number of nodes,say n.(Nodes are numbered as 0,1,2,...(n-1) )
Followed by n*n weighted matrix. Disconnected egdes are represented by negative weight.
Last line contains the source node.(i.e, the node from which the BFS should begin)


### Draw Graph ###


Graph is first drawn from the weighted matrix input from the user with weights shown. Edges are marked with black.
visualization of the input graph-
![1](https://user-images.githubusercontent.com/22571531/27984139-48d91928-63eb-11e7-9634-fed45cec799a.png)


### BFS traversal ###

Iterative BFS is performed, using a queue. Each time an edge is encountered, 
it is marked with red on the graph through the line -
```
nx.draw_networkx_edges(G,pos,edgelist=[(curr_node,i)],width=2.5,alpha=0.6,edge_color='r')

```
Visualization of the result-
![2](https://user-images.githubusercontent.com/22571531/27984141-4d665e42-63eb-11e7-97e6-49f28ff1552e.png)

### Complexity ###

Time: 0(m+n)                                                                                                        
where m - number of edges                                                                                
n - number of nodes 




================================================
FILE: BFS/bfs.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
 


#BFS traversal 
def BFS(G, source, pos): 
	visited = [False]*(len(G.nodes()))
 	queue = []		#a queue for BFS traversal
	queue.append(source)
	visited[source] = True
	while queue:
		curr_node = queue.pop(0)
		for i in G[curr_node]:  #iterates through all the possible vertices adjacent to the curr_node
			if visited[i] == False:
				queue.append(i)
				visited[i] = True
				# nx.draw_networkx_edges(G, pos, edgelist = [(curr_node,i)], width = 2.5, alpha = 0.6, edge_color = 'r')
	return



#takes input from the file and creates a weighted graph
def CreateGraph():
	G = nx.DiGraph()
	f = open('input.txt')
	n = int(f.readline())
	wtMatrix = []
	for i in range(n):
		list1 = list(map(int, (f.readline()).split()))
		wtMatrix.append(list1)
	source = int(f.readline()) #source vertex from where BFS has to start
	#Adds egdes along with their weights to the graph 
	for i in range(n):
		for j in range(len(wtMatrix[i])):
			if wtMatrix[i][j] > 0:
					G.add_edge(i, j, length = wtMatrix[i][j]) 
	return G, source



#draws the graph and displays the weights on the edges
def DrawGraph(G):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True)  #with_labels=true is to show the node number in the output graph
	edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
	return pos



#main function
if __name__== "__main__":
	G,source = CreateGraph()
	pos = DrawGraph(G)
	BFS(G, source, pos)
	plt.show()



================================================
FILE: BFS/input.txt
================================================
4
0 5 10 5
0 0 5 0
0 10 0 0
0 0 10 0
0


================================================
FILE: BellmanFord/BellmanFord.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import sys

inf = float('inf')

#function that performs Bellman-Ford algorithm on the graph G,with source vertex as source
def bellmanFord(G, source, pos):
	V = len(G.nodes()) # V denotes the number of vertices in G
	dist = [] # dist[i] will hold the shortest distance from source to i
	parent = [None]*V # parent[i] will hold the node from which i is reached to, in the shortest path from source

	for i in range(V):
		dist.append(inf)

	parent[source] = -1; #source is itself the root, and hence has no parent
	dist[source] = 0;

	for i in range(V-1):
		for u, v, d in G.edges(data = True): # Relaxation is the most important step in Bellman-Ford. It is what increases the accuracy of the distance to any given vertex. Relaxation works by continuously shortening the calculated distance between vertices comparing that distance with other known distances.
			if dist[u] + d['length'] < dist[v]: #Relaxation Equation
				dist[v] = d['length'] + dist[u]
				parent[v] = u

	#marking the shortest path from source to each of the vertex with red, using parent[]
	for v in range(V):
		if parent[v] != -1: #ignore the parent of root node
			if (parent[v], v) in G.edges():
				nx.draw_networkx_edges(G, pos, edgelist = [(parent[v], v)], width = 2.5, alpha = 0.6, edge_color = 'r')
	return

#takes input from the file and creates a weighted graph
def createGraph():
	G = nx.DiGraph()
	f = open('input.txt')
	n = int(f.readline())
	wtMatrix = []
	for i in range(n):
		list1 = map(int, (f.readline()).split())
		wtMatrix.append(list1)
	source = int(f.readline()) #source vertex for BellmanFord algo
	#Adds egdes along with their weights to the graph
	for i in range(n) :
		for j in range(n) :
			if wtMatrix[i][j] > 0 :
					G.add_edge(i, j, length = wtMatrix[i][j])
	return G, source


#draws the graph and displays the weights on the edges
def DrawGraph(G):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True)  #with_labels=true is to show the node number in the output graph
	edge_labels = dict([((u, v), d['length']) for u, v, d in G.edges(data = True)])
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
	return pos

#main function
if __name__ == "__main__":
	G, source = createGraph()
	pos = DrawGraph(G)
	bellmanFord(G, source, pos)
	plt.show()


================================================
FILE: BellmanFord/input.txt
================================================
5
0 2 7 -1 -1
-1 0 3 8 5
-1 2 0 1 -1
-1 -1 -1 0 4
-1 -1 -1 5 0
0


================================================
FILE: DFS/README.md
================================================
# Visualisation of DFS traversal using networkx library

### INPUT ###

Graph is first drawn from the weighted matrix input from the user. 
Input is taken from the file 
#### input.txt ####

Sample input
```
 4
 0 5 0 5
 5 0 5 0
 0 5 0 5
 5 0 5 0
 0

```
First line contains the number of nodes,say n.(Nodes are numbered as 0,1,2,...(n-1) )
Followed by n*n weighted matrix. Disconnected egdes are represented by negative weight.
Last line contains the source node.(i.e, the node from which the DFS should begin)

Visualization of the input graph-
![1](https://user-images.githubusercontent.com/22571531/27984144-547decd6-63eb-11e7-9ddc-487d976b0fec.png)

### DFS traversal ###

Recursive DFS is performed, resulting DFS forests are stored in a stack. 

### Visulization of DFS path ###

The stack is then used to mark the DFS traversed edges with a different colour(Here, Red. So, as to distinguish itself from the rest).
Visualization of the result-
![2](https://user-images.githubusercontent.com/22571531/27984145-593846ae-63eb-11e7-91bc-4c69ba5ba12a.png)

### Complexity ###

Time: 0(m+n)                                                                                                        
where m - number of edges                                                                                
n - number of nodes                                                                                          



================================================
FILE: DFS/dfs_visual.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
 


#utility fucntion used by DFS which does recursive depth first search 
def DFSUtil(G, v, visited, sl): 
	visited[v] = True
	sl.append(v) 
	for i in G[v]:
		if visited[i] == False:
			DFSUtil(G, i, visited, sl)
	return sl
 


#DFS traversal 
def DFS(G, source): 
	visited = [False]*(len(G.nodes()))
 	sl = []		#a list that stores dfs forest starting with source node
 	dfs_stk = [] #A nested list that stores all the DFS Forest's
	dfs_stk.append(DFSUtil(G, source, visited, sl))
	for i in range(len(G.nodes())):
		if visited[i] == False:
			sl = []
			dfs_stk.append(DFSUtil(G, i, visited, sl))
	return dfs_stk
			


#takes input from the file and creates a weighted graph
def CreateGraph():
	G = nx.DiGraph()
	f = open('input.txt')
	n = int(f.readline())
	wtMatrix = []
	for i in range(n):
		list1 = map(int,(f.readline()).split())
		wtMatrix.append(list1)
	source = int(f.readline()) #source vertex from where DFS has to start
	#Adds egdes along with their weights to the graph 
	for i in range(n):
		for j in range(n):
			if wtMatrix[i][j] > 0:
					G.add_edge(i, j, length = wtMatrix[i][j]) 
	return G,source



#marks all edges traversed through DFS with red
def DrawDFSPath(G, dfs_stk):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True)  #with_labels=true is to show the node number in the output graph
	edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
	for i in dfs_stk:
		#if there is more than one node in the dfs-forest, then print the corresponding edges
		if len(i) > 1:
			for j in i[ :(len(i)-1)]:
				if i[i.index(j)+1] in G[j]:
					nx.draw_networkx_edges(G, pos, edgelist = [(j,i[i.index(j)+1])], width = 2.5, alpha = 0.6, edge_color = 'r')
				else:
					#if in case the path was reversed because all the possible neighbours were visited, we need to find the adj node to it.
					for k in i[1::-1]: 
						if k in G[j]:
							nx.draw_networkx_edges(G, pos, edgelist = [(j,k)], width = 2.5, alpha = 0.6, edge_color = 'r')
							break



#main function
if __name__ == "__main__":
	G, source = CreateGraph()
	dfs_stk = DFS(G, source)
	DrawDFSPath(G, dfs_stk)
	plt.show()




================================================
FILE: DFS/input.txt
================================================
4
0 5 0 5
5 0 5 0
0 5 0 5
5 0 5 0
0


================================================
FILE: Dijsktra's/README.md
================================================
# Visualisation of Dijsktra's algorithm using networkx library

### INPUT ###


Input is taken from the file 
#### input.txt ####

Sample input
```
  5
  0 2 7 -1 -1
  -1 0 3 8 5
  -1 2 0 1 -1
  -1 -1 -1 0 4
  -1 -1 -1 5 0
  0


```
First line contains the number of nodes,say n.(Nodes are numbered as 0,1,2,...(n-1) )
Followed by n*n weighted matrix. Disconnected egdes are represented by negative weight.
Last line contains the source node.(i.e, the node from which the rest of the nodes should be reached)

### Draw Graph ###


Graph is first drawn from the weighted matrix input from the user with weights shown. Edges are marked with black.



### Dijsktras algorithm ###

DDijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph. 

Here, given the source node, the algorithm finds the shortest path from the source node to each of the remaining nodes. 

To understand this better, consider the above input.
Source node is 0.

The graph, initially.

![1](https://user-images.githubusercontent.com/22571531/27195526-ca5dd872-5224-11e7-9b34-e669c7082a6e.png)

We use the following 3 lists:

#### dist ####
 dist[i] will hold the shortest distance from source to i.                                 
#### parent ####                               
parent[i] will hold the node from which node i is reached to, in the shortest path from source.                          
#### sptSet ####                         
sptSet[i] will hold true if vertex i is included in shortest path tree.                           

#### Initial values: ####
```
dist   = [0, inf ,inf, inf, inf]
parent = [-1, None, None, None]                        
sptSet = [True, False, False, False, False]
```

#### After the first iteration: ####

Node 1 and Node 2 can be reached directly from source node,i.e, 0 with a distance of 2 and 7 respectively. Hence they are updated accordingly.

```
dist   = [0, 2, 7, inf, inf]
parent = [-1, 0, 0, None, None] 
sptSet = [True, False, False, False, False]
```

Minimum most distance of those where sptSet[i] == False, is node 1.
Hence, the node is now included in the shorted path tree, hence sptSet[1] is set to True.

![2](https://user-images.githubusercontent.com/22571531/27195530-cd783296-5224-11e7-87f5-a404a94fed84.png)


#### After the second iteration: ####

```
dist   = [0, 2, 5, 10, 7]
parent = [-1, 0, 1, 1, 1]
sptSet = [True, True, False, False, False]
```

![3](https://user-images.githubusercontent.com/22571531/27195531-d081e824-5224-11e7-8993-81f2dc43c30f.png)

#### After the third iteration: ####

```
dist   = [0, 2, 5, 6, 7]
parent = [-1, 0, 1, 2, 1]
sptSet = [True, True, True, False, False]
```

![4](https://user-images.githubusercontent.com/22571531/27195536-d310f896-5224-11e7-8a75-eb5e883bc37b.png)

#### After the fourth iteration: ####

```
dist   = [0, 2, 5, 6, 7]
parent = [-1, 0, 1, 2, 1]
sptSet = [True, True, True, True, False]
```

Here, the red edges denote the shortest path from source node to the rest of the nodes.

![5](https://user-images.githubusercontent.com/22571531/27195545-d8cfdf68-5224-11e7-8ee9-1b2d38e1d6ad.png)

#### Complexity ####
Time : O(V^2)                                                           
V - number of Vertices                                


================================================
FILE: Dijsktra's/dijsktras.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import sys
 


#utility function that returns the minimum distance node
def minDistance(dist, sptSet, V):
   	min = sys.maxsize #assigning largest numeric value to min
   	for v in range(V):
   		if sptSet[v] == False and dist[v] <= min:
   			min = dist[v]
   			min_index = v
	return min_index



#function that performs dijsktras algorithm on the graph G,with source vertex as source
def dijsktras(G, source, pos):
	V = len(G.nodes()) # V denotes the number of vertices in G
	dist = [] # dist[i] will hold the shortest distance from source to i
	parent = [None]*V # parent[i] will hold the node from which i is reached to, in the shortest path from source
	sptSet = [] # sptSet[i] will hold true if vertex i is included in shortest path tree
	#initially, for every node, dist[] is set to maximum value and sptSet[] is set to False
	for i in range(V):
		dist.append(sys.maxsize)
		sptSet.append(False)
	dist[source] = 0
	parent[source]= -1 #source is itself the root, and hence has no parent
	for count in range(V-1):
		u = minDistance(dist, sptSet, V) #pick the minimum distance vectex from the set of vertices
		sptSet[u] = True
		#update the vertices adjacent to the picked vertex
		for v in range(V):
			if (u, v) in G.edges():
				if sptSet[v] == False and dist[u] != sys.maxsize and dist[u] + G[u][v]['length'] < dist[v]:
					dist[v] = dist[u] + G[u][v]['length']
					parent[v] = u
	#marking the shortest path from source to each of the vertex with red, using parent[]
	for X in range(V):
		if parent[X] != -1: #ignore the parent of root node 
			if (parent[X], X) in G.edges():
				nx.draw_networkx_edges(G, pos, edgelist = [(parent[X], X)], width = 2.5, alpha = 0.6, edge_color = 'r')
	return



#takes input from the file and creates a weighted graph
def CreateGraph():
	G = nx.DiGraph()
	f = open('input.txt')
	n = int(f.readline())
	wtMatrix = []
	for i in range(n):
		list1 = map(int, (f.readline()).split())
		wtMatrix.append(list1)
	source = int(f.readline()) #source vertex for dijsktra's algo 
	#Adds egdes along with their weights to the graph 
	for i in range(n) :
		for j in range(n) :
			if wtMatrix[i][j] > 0 :
					G.add_edge(i, j, length = wtMatrix[i][j]) 
	return G, source



#draws the graph and displays the weights on the edges
def DrawGraph(G):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True)  #with_labels=true is to show the node number in the output graph
	edge_labels = dict([((u, v), d['length']) for u, v, d in G.edges(data = True)])
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
	return pos



#main function
if __name__ == "__main__":
	G,source = CreateGraph()
	pos = DrawGraph(G)
	dijsktras(G, source, pos)
	plt.show()



================================================
FILE: Dijsktra's/input.txt
================================================
  5
  0 2 7 -1 -1
  -1 0 3 8 5
  -1 2 0 1 -1
  -1 -1 -1 0 4
  -1 -1 -1 5 0
  0



================================================
FILE: Egocentric Network/egocentric_network_1.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
 

def EgocentricNetwork(G,v):
	egocentric_network_edge_list = []
	egocentric_network_node_list = [v]
	for i in G.neighbors(v):
		egocentric_network_node_list.append(i)
		egocentric_network_edge_list.append((v,i))
	return egocentric_network_edge_list,egocentric_network_node_list



#takes input from the file and creates a graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	for i in range(n):
		G.add_node(i+1)
	no_of_edges = int(f.readline())
	for i in range(no_of_edges):
		graph_edge_list = f.readline().split()
		G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1])) 
	vert = int(f.readline())
	return G, vert



#draws the graph and displays the weights on the edges
def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list, vert):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8)  #with_labels=true is to show the node number in the output graph
	nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red')
	nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5)
	nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8)
	return pos


def CentralityMeasures(G):
	# Betweenness centrality
	bet_cen = nx.betweenness_centrality(G)
	# Closeness centrality
	clo_cen = nx.closeness_centrality(G)
	# Eigenvector centrality
	eig_cen = nx.eigenvector_centrality(G)
	# Degree centrality
	deg_cen = nx.degree_centrality(G)
	#print bet_cen, clo_cen, eig_cen
	print "# Betweenness centrality:" + str(bet_cen)
	print "# Closeness centrality:" + str(clo_cen)
	print "# Eigenvector centrality:" + str(eig_cen)
	print "# Degree centrality:" + str(deg_cen)


#main function

if __name__== "__main__":
	G,vert = CreateGraph()
	egocentric_network_edge_list,egocentric_network_node_list = EgocentricNetwork(G,vert)
	DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list, vert)
	CentralityMeasures(G)
	plt.show()



================================================
FILE: Egocentric Network/egocentric_network_1_5.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import itertools
 

def EgocentricNetwork(G,v):
	
	egocentric_network_edge_list = []
	egocentric_network_node_list = [v]
	for i in G.neighbors(v):
		egocentric_network_node_list.append(i)
		egocentric_network_edge_list.append((v,i))
	egocentric_network_node_list.sort()
	egocentric_network_edge_list = list(tuple(sorted(p)) for p in egocentric_network_edge_list)

	for i in list(itertools.combinations(egocentric_network_node_list, 2)): #generates all possible pairs of nodes
		if i in G.edges() and i not in egocentric_network_edge_list:
			egocentric_network_edge_list.append(i)

	return egocentric_network_edge_list,egocentric_network_node_list



#takes input from the file and creates a graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	for i in range(n):
		G.add_node(i+1)
	no_of_edges = int(f.readline())
	for i in range(no_of_edges):
		graph_edge_list = f.readline().split()
		G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1])) 
	vert = int(f.readline())
	return G, vert



#draws the graph and displays the weights on the edges
def DrawGraph(G, egocentric_network_edge_list, egocentric_network_node_list, vert):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8)  #with_labels=true is to show the node number in the output graph
	nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red')
	nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5)
	nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8)
	return pos


def CentralityMeasures(G):
	# Betweenness centrality
	bet_cen = nx.betweenness_centrality(G)
	# Closeness centrality
	clo_cen = nx.closeness_centrality(G)
	# Eigenvector centrality
	eig_cen = nx.eigenvector_centrality(G)
	# Degree centrality
	deg_cen = nx.degree_centrality(G)
	#print bet_cen, clo_cen, eig_cen
	print "# Betweenness centrality:" + str(bet_cen)
	print "# Closeness centrality:" + str(clo_cen)
	print "# Eigenvector centrality:" + str(eig_cen)
	print "# Degree centrality:" + str(deg_cen)


#main function
if __name__== "__main__":
	G, vert = CreateGraph()
	egocentric_network_edge_list,egocentric_network_node_list = EgocentricNetwork(G, vert)
	DrawGraph(G,egocentric_network_edge_list, egocentric_network_node_list, vert)
	CentralityMeasures(G)
	plt.show()



================================================
FILE: Egocentric Network/egocentric_network_2.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import itertools
 

def EgocentricNetwork(G,v):
	
	egocentric_network_edge_list = []
	egocentric_network_node_list = [v]
	for i in G.neighbors(v):
		egocentric_network_node_list.append(i)
		egocentric_network_edge_list.append((v,i))
	egocentric_network_node_list.sort()
	egocentric_network_edge_list = list(tuple(sorted(p)) for p in egocentric_network_edge_list)

	for i in list(itertools.combinations(egocentric_network_node_list, 2)): #generates all possible pairs of nodes
		if i in G.edges() and i not in egocentric_network_edge_list:
			egocentric_network_edge_list.append(i)

	
	temp = []
	temp.extend(egocentric_network_node_list)

	for i in temp:#print i," ",G.neighbors(i)
		for j in G.neighbors(i):
			if j not in egocentric_network_node_list:
				egocentric_network_node_list.append(j)
			if (j,i) in G.edges() and (j,i) not in egocentric_network_edge_list:
				egocentric_network_edge_list.append((j,i))
			elif (i,j) in G.edges() and (i,j) not in egocentric_network_edge_list:
				egocentric_network_edge_list.append((i,j))
	print egocentric_network_edge_list
	print egocentric_network_node_list
	return egocentric_network_edge_list,egocentric_network_node_list



#takes input from the file and creates a graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	for i in range(n):
		G.add_node(i+1)
	no_of_edges = int(f.readline())
	for i in range(no_of_edges):
		graph_edge_list = f.readline().split()
		G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1])) 
	vert = int(f.readline())
	return G, vert



#draws the graph and displays the weights on the edges
def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.2)  #with_labels=true is to show the node number in the output graph
	nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'blue')
	nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'blue', alpha = 0.5)
	return pos


def DrawGraph(G, egocentric_network_edge_list, egocentric_network_node_list, vert):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8)  #with_labels=true is to show the node number in the output graph
	nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red')
	nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5)
	nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8)
	return pos


def CentralityMeasures(G):
	# Betweenness centrality
	bet_cen = nx.betweenness_centrality(G)
	# Closeness centrality
	clo_cen = nx.closeness_centrality(G)
	# Eigenvector centrality
	eig_cen = nx.eigenvector_centrality(G)
	# Degree centrality
	deg_cen = nx.degree_centrality(G)
	#print bet_cen, clo_cen, eig_cen
	print "# Betweenness centrality:" + str(bet_cen)
	print "# Closeness centrality:" + str(clo_cen)
	print "# Eigenvector centrality:" + str(eig_cen)
	print "# Degree centrality:" + str(deg_cen)


#main function
if __name__== "__main__":
	G,vert = CreateGraph()
	egocentric_network_edge_list,egocentric_network_node_list = EgocentricNetwork(G,vert)
	DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list, vert)
	CentralityMeasures(G)
	plt.show()



================================================
FILE: Egocentric Network/input.txt
================================================
10
11
1 2
1 4
1 3
3 9
3 6
6 8
8 9
6 9
4 6
4 5
5 7
9

================================================
FILE: Graph Coloring/README.md
================================================
# Visualisation of Graph Coloring Problem using networkx library

### Graph Coloring ###

 Graph Coloring Problem is an NP complete problem where "colors" are assigned to elements of a graph(edge ,node or face) subject to certain constraints.

 This is an illustration of Vertex Coloring problem. The problem is that, given an undirected graph, assign colors to each node such that no two ajacent nodes have the same color. It also involves minimization of the number of colors used.

 Basic approach:

 Step 1: Assign first color to the first vertex
 Step 2: For each of the remaining vertices, color the vertex with the lowest numbered color which has not yet been used for any of its neighbouring vertices.

 The above approach is a Greedy approach. It doesn't guarantee to use minimum number of color's each time. One way to improve this is by ordering the vertices in the decreasing order of their valency. And apply node coloring in that order. By doing so, the node with maximum color conflicts will be resolved first, and hence works better. This is Welsh - Powell algorithm.


#### Working ####

For the sample input below:

```
16
0 7
0 1
1 3
3 2
3 8
3 10
7 8
7 9
7 10
7 6
8 9
9 10
6 5
10 4
5 4
6 10
```
Visualization of the input graph:

![1](https://user-images.githubusercontent.com/22571531/28072420-93b63840-6670-11e7-8178-45c47e8fddfe.png)


Visualization of the result after node coloring.                                                  
Following 4 colors have been used:                                                          
Blue : 0, 3, 5                                                              
Purple : 1, 2, 4, 6, 9                                                              
Green : 7                                                                  
Yellow : 8, 10                                                        

![2](https://user-images.githubusercontent.com/22571531/28072424-9638f80a-6670-11e7-99ba-7b83ab92193c.png)

#### Complexity ####

Time: O(N^2 + E)                                                                                                          
N - number of Nodes                                              
E - number of Edges                                               



 





================================================
FILE: Graph Coloring/graph_coloring.py
================================================
import networkx as nx
import matplotlib.pyplot as plt


#implementation of welsh_powell algorithm
def welsh_powell(G):
	#sorting the nodes based on it's valency
	node_list = sorted(G.nodes(), key =lambda x:G.neighbors(x))
	col_val = {} #dictionary to store the colors assigned to each node
	col_val[node_list[0]] = 0 #assign the first color to the first node
	# Assign colors to remaining N-1 nodes
	for node in node_list[1:]:
		available = [True] * len(G.nodes()) #boolean list[i] contains false if the node color 'i' is not available

		#iterates through all the adjacent nodes and marks it's color as unavailable, if it's color has been set already
		for adj_node in G.neighbors(node): 
			if adj_node in col_val.keys():
				col = col_val[adj_node]
				available[col] = False
		clr = 0
		for clr in range(len(available)):
			if available[clr] == True:
				break
		col_val[node] = clr
	print col_val
	return col_val

        



#takes input from the file and creates a undirected graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	for i in range(n):
		graph_edge_list = f.readline().split()
		G.add_edge(graph_edge_list[0], graph_edge_list[1]) 
	return G


#draws the graph and displays the weights on the edges
def DrawGraph(G,col_val):
	pos = nx.spring_layout(G)
	values = [col_val.get(node, 'blue') for node in G.nodes()]
	nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'black' ,width = 1, alpha = 0.7)  #with_labels=true is to show the node number in the output graph




#main function
if __name__ == "__main__":
	G = CreateGraph()
	col_val = welsh_powell(G)
	DrawGraph(G,col_val)
	plt.show()

================================================
FILE: Graph Coloring/input.txt
================================================
16
0 7
0 1
1 3
3 2
3 8
3 10
7 8
7 9
7 10
7 6
8 9
9 10
6 5
10 4
5 4
6 10

================================================
FILE: Greedy BFS/README.md
================================================


# Visualisation of Greedy BFS using networkx library

### Greedy Best First Search ###

Best-first search is a search algorithm which explores a graph by expanding the most promising node chosen according to a specified rule. A greedy algorithm is one that chooses the best-looking option at each step. Hence, greedy best-first search algorithm combines the features of both mentioned above. It is known to be moving towards the direction of the target, in each step. (PS: There is no visiting back in path, as it is Greedy)

#### Heuristic function

Greedy BFS uses heuristics to the pick the "best" node.

A heuristic is an approximate measure of how close you are to the target. In short, h can be any function at all. We will require only that h(n) = 0 if n is a goal.

#### BFS v/s Greedy BFS

BFS expands the most promising node first(by looking at it's proximity to the source node).Hence, the solution is thorough. It might have to return back in path if a dead end is reached.
Whereas, Greedy BFS uses heuristics to prioritize nodes closer to target. Hence, the solution is faster(but not necessarily optimal). There is no returning back in the path.

Often with large data sets, search algorithms could get computationally expensive with thorough approaches. Hence, we resort to approximation algorithms like Greedy BFS.

### Greedy BFS Algorithm

Heuristic functions are clearly problem-specific.

Let us understand this better through an example. 

![Romania map](https://user-images.githubusercontent.com/22571531/27821959-ac69755a-60c1-11e7-8286-951cd1c0437f.png)

Source: Artificial Intelligence A Modern Approach
        by Stuart J. Russell and Peter Norvig 

Given here is the map of Romania with cities and distance between them. We need to find the shortest route from Arad to Bucharest. 

The heurestics that we are using here is the straight-line distance from the city to the goal(Here, Bucharest). Note that, this straight line distance is obtained only by knowing the map coordinates of the 2 cities. 


#### Input

Input is taken from the file 
```
input.txt
```

Each line in the input is of the form 
```
city1 city2 dist
```
It denotes each element of the adjacency list. That is, dist is the distance between city1 and city2. An undireced graph is drawn depicting the map of Romania.
Starting city: Arad
Goal city: Bucharest

Heuristics is loaded from the file
```
heuristics.txt
```
Each line is of the form
```
city h
```
'h' stands for the heuristics value(here, the straight line distnace) from the city 'city' to goal city(here, Bucharest)

#### Working: 

Starting from source city, we choose the next city which is the closest to the Goal city amongst all it's neighbours(based on the heuristics function). We terminate, once we've reached the goal city.

Here, Arad is the starting city. The first node to be expanded from Arad will be Sibiu, because it is closer to Bucharest than either Zerind or Timisoara. The next node to be expanded will be Fagaras, because it is closest. Fagaras in turn generates Bucharest, which is the goal.

Here, is the resultant graph.                                              
Green coloured node denotes the starting city(Here, Arad).                                             
Red coloured node denotes the goal city(Here, Bucharest).                                                           
Edges marked with black is the route from Arad to Bucharest generated by the greedy bfs algorithm.

![shortest route](https://user-images.githubusercontent.com/22571531/27821965-b12030d4-60c1-11e7-9e37-9388e4dd8751.png)

#### Complexity ####

Time: O(b^m)                                                                
b - Branching factor, the average number of successors per state        
m - maximum depth of the search 


================================================
FILE: Greedy BFS/greedy_bfs.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import Queue as Q
 
 

def getPriorityQueue(list):
	q = Q.PriorityQueue()
	for node in list:
		q.put(Ordered_Node(heuristics[node],node))
	return q,len(list)



def greedyBFSUtil(G, v, visited, final_path, dest, goal): 
	if goal == 1:
		return goal
	visited[v] = True
	final_path.append(v)
	if v == dest:
		goal = 1
	else:
		pq_list = []
		pq,size = getPriorityQueue(G[v])
		for i in range(size):
			pq_list.append(pq.get().description)
		for i in pq_list:
			if goal != 1:
				#print "current city:", i
				if visited[i] == False :
					goal = greedyBFSUtil(G, i, visited, final_path, dest, goal)
	return goal


 
def greedyBFS(G, source, dest, heuristics, pos): 
	visited = {}
	for node in G.nodes():
		visited[node] = False
 	final_path = []
	goal = greedyBFSUtil(G, source, visited, final_path, dest, 0)
	prev = -1
	for var in final_path:
		if prev != -1:
			curr = var
			nx.draw_networkx_edges(G, pos, edgelist = [(prev,curr)], width = 2.5, alpha = 0.8, edge_color = 'black')
			prev = curr
		else:
			prev = var
	return



class Ordered_Node(object):
	def __init__(self, priority, description):
		self.priority = priority
		self.description = description
		return
	def __cmp__(self, other):
		return cmp(self.priority, other.priority)

def getHeuristics(G):
	heuristics = {}
	f = open('heuristics.txt')
	for i in G.nodes():
		node_heuristic_val = f.readline().split()
		heuristics[node_heuristic_val[0]] = node_heuristic_val[1]
	return heuristics



#takes input from the file and creates a weighted graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	for i in range(n):
		graph_edge_list = f.readline().split()
		G.add_edge(graph_edge_list[0], graph_edge_list[1], length = graph_edge_list[2]) 
	source, dest= f.read().splitlines()
	return G, source, dest



def DrawPath(G, source, dest):
	pos = nx.spring_layout(G)
	val_map = {}
	val_map[source] = 'green'
	val_map[dest] = 'red'
	values = [val_map.get(node, 'blue') for node in G.nodes()]
	nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'b' ,width = 1, alpha = 0.7)  #with_labels=true is to show the node number in the output graph
	edge_labels = dict([((u, v,), d['length']) for u, v, d in G.edges(data = True)])
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.5, font_size = 11) #prints weight on all the edges
	return pos



#main function
if __name__ == "__main__":
	G, source,dest = CreateGraph()
	heuristics = getHeuristics(G)
	pos = DrawPath(G, source, dest)
	greedyBFS(G, source, dest, heuristics, pos)
	plt.show()






================================================
FILE: Greedy BFS/heuristics.txt
================================================
Arad 366
Bucharest 0
Craiova 160
Dobreta 242
Eforie 161
Fagaras 178
Giurgiu 77
Hirsova 151
Iasi 226
Lugoj 244
Mehadia 241
Neamt 234
Oradea 380
Pitesti 98
Rimnicu_Vilcea 193
Sibiu 253
Timisoara 329
Urziceni 80
Vaslui 199
Zerind 374

================================================
FILE: Greedy BFS/input.txt
================================================
23
Arad Sibiu 140
Arad Timisoara 118
Arad Zerind 75
Bucharest Fagaras 211
Bucharest Giurgiu 90
Bucharest Pitesti 101
Bucharest Urziceni 85
Craiova Dobreta 120
Craiova Pitesti 138
Craiova Rimnicu_Vilcea 146
Dobreta Mehadia 75
Eforie Hirsova 86
Fagaras Sibiu 99
Hirsova Urziceni 98
Iasi Neamt 87
Iasi Vaslui 92
Lugoj Mehadia 70
Lugoj Timisoara 111
Oradea Zerind 71
Oradea Sibiu 151
Pitesti Rimnicu_Vilcea 97
Rimnicu_Vilcea Sibiu 80
Urziceni Vaslui 142
Arad
Bucharest

================================================
FILE: K Centers Problem/README.md
================================================
# Visualisation of K - Centers Problem using networkx library

### K - Center ###

 K - Center problem (also known as Metric K - Center problem) is a NP - Hard Problem where given n cities, one needs to choose k (k<=n) centers, such that maximum distance of a city to the center is minimized. 

 In layman terms,say we need to bulid k warehouses given a map of n connected cities. The best way to build a warehouse, is by keeping in mind that, it must be closest to the cities. In other words, the maximum distance of a city to the warehouse must be minimal.


 Greedy approach:

 Here, is an illustration of the simple greedy algorithm which has an approximation factor of 2. It works on the basic idea of choosing the city which is farthest from the current set of centers. 

 Step 1: Pick an arbitrary center,c<sub>1</sub>.                                                                  
 Step 2: For every remaining cities C<sub>1</sub>,C<sub>2</sub>,.. C<sub>N-1</sub>, compute minimum distnace from the centers chosen already.                                                                                                    
 Step 3: Pick the new center with the highest distance from already chosen centers, that is max((dist(c<sub>1</sub>, C<sub>1</sub>), dist(c<sub>1</sub>,C<sub>2</sub>), ... dist(c<sub>1</sub>, C<sub>N-1</sub>)).                         
 Step 4: Continue this till all the k centers are found.                                            



#### Working ####

For the sample input below:

```
4
0 10 7 6
10 0 8 5
7 8 0 12
6 5 12 0
3
```
Visualization of the input graph:

![1](https://user-images.githubusercontent.com/22571531/28249724-dcc08a16-6a78-11e7-8fbe-21905190307e.png)

Visualization of the result :                                     

Here, the red colored nodes denote the centers.                                                       
![2](https://user-images.githubusercontent.com/22571531/28249726-e1255e42-6a78-11e7-9dd2-13b4751c2939.png)

#### Complexity ####

Time: O(n*k)                                                                                                          
n - number of Cities                                              
k - number of Centers
 





================================================
FILE: K Centers Problem/input.txt
================================================
4
0 10 7 6
10 0 8 5
7 8 0 12
6 5 12 0
2

================================================
FILE: K Centers Problem/k_centers_problem.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import operator



def k_centers(G, n):
	centers = []
	cities = G.nodes()
	#add an arbitrary node, here, the first node,to the centers list
	centers.append((G.nodes())[0])
	cities.remove(centers[0]) 
	n = n-1 #since we have already added one center
	#choose n-1 centers
	while n!= 0:
		city_dict = {}
		for cty in cities:
			min_dist = float("inf")
			for c in centers:
				min_dist = min(min_dist,G[cty][c]['length'])
			city_dict[cty] = min_dist
		#print city_dict
		new_center = max(city_dict, key = lambda i: city_dict[i])
		#print new_center
		centers.append(new_center)
		cities.remove(new_center)
		n = n-1
	#print centers
	return centers



#takes input from the file and creates a weighted undirected graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline()) #n denotes the number of cities
	wtMatrix = []
	for i in range(n):
		list1 = map(int, (f.readline()).split())
		wtMatrix.append(list1)
	#Adds egdes along with their weights to the graph 
	for i in range(n) :
		for j in range(n)[i:] :
				G.add_edge(i, j, length = wtMatrix[i][j]) 
	noc = int(f.readline()) #noc,here,denotes the number of centers
	return G, noc



#draws the graph and displays the weights on the edges
def DrawGraph(G, centers):
	pos = nx.spring_layout(G)
 	color_map = ['blue'] * len(G.nodes())
 	#all the center nodes are marked with 'red'
 	for c in centers:
 		color_map[c] = 'red'
	nx.draw(G, pos, node_color = color_map, with_labels = True)  #with_labels=true is to show the node number in the output graph
	edge_labels = nx.get_edge_attributes(G, 'length')
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
	


#main function
if __name__ == "__main__":
	G,n = CreateGraph()
	centers = k_centers(G, n)
	DrawGraph(G, centers)
	plt.show()



================================================
FILE: Kruskal's/README.md
================================================
# Visualisation of Kruskal's algorithm using networkx library

### INPUT ###


Input is taken from the file 
#### input.txt ####

Sample input
```
  5
  0 2 7 -1 -1
  2 0 3 8 5
  7 3 0 1 -1
  -1 8 1 0 4
  -1 5 -1 4 0

```
First line contains the number of nodes,say n.(Nodes are numbered as 0,1,2,...(n-1) )
Followed by n*n weighted matrix. Disconnected edges are represented by negative weight.

### Draw Graph ###


Graph is first drawn from the weighted matrix input from the user with weights shown. Edges are marked with black.



### Kruskal's algorithm ###

Kruskal's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected garph. 

The algorithm operates by adding the egdes one by one in the order of their increasing lengths, so as to form a tree. Egdes are rejected if it's addition to the tree, forms a cycle. This continues till we have V-1 egdes in the tree. (V stands for the number of vertices).

To understand this better, consider the above input.

The graph, initially.

![1](https://user-images.githubusercontent.com/22571531/27430044-b959f994-5764-11e7-9b3e-aa0c10dc98e9.png)
                           

#### After the first iteration: ####

The smallest edge is of length 1, connecting Node 2 and Node 3. Since it is the first edge, it is added directly to the tree.


![2](https://user-images.githubusercontent.com/22571531/27430048-bcf86eb4-5764-11e7-8f03-397f601338b2.png)


#### After the second iteration: ####

Next smallest edge is of length 2, connecting Node 0 and Node 1. Since it's addition doesn't result in a cycle, it is added to the tree.


![3](https://user-images.githubusercontent.com/22571531/27430058-c0a1da78-5764-11e7-8a0a-a29ab5442d80.png)

#### After the third iteration: ####

Next smallest edge is of length 3, connecting Node 1 and Node 2. Since it's addition doesn't result in a cycle, it is added to the tree.

![4](https://user-images.githubusercontent.com/22571531/27430069-c607466a-5764-11e7-9a2e-7d60e5d50254.png)

#### After the fourth iteration: ####

Next smallest edge is of length 4, connecting Node 3 and Node 4. Since it's addition doesn't result in a cycle, it is added to the tree.

Now we have 4 edges, hence we stop the iteration.
Final graph, with red edges denoting the minimum spanning tree.

![5](https://user-images.githubusercontent.com/22571531/27430080-ce205b20-5764-11e7-8bca-20f452d8b20d.png)

#### Complexity ####

Time: O(V^2)                                                                 
V - Number of vertices                                          

================================================
FILE: Kruskal's/input.txt
================================================
  5
  0 2 7 -1 -1
  2 0 3 8 5
  7 3 0 1 -1
  -1 8 1 0 4
  -1 5 -1 4 0

================================================
FILE: Kruskal's/kruskals_quick_union.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import sys



# A utility function that return the smallest unprocessed edge
def getMin(G, mstFlag):
    min = sys.maxsize  # assigning largest numeric value to min
    for i in [(u, v, edata['length']) for u, v, edata in G.edges( data = True) if 'length' in edata ]:
    	if mstFlag[i] == False and i[2] < min:
    		min = i[2]
    		min_edge = i
    return min_edge

	

# A utility function to find root or origin of the node i in MST
def findRoot(parent, i):
    if parent[i] == i:
        return i
    return findRoot(parent, parent[i])



# A function that does union of set x and y based on the order
def union(parent, order, x, y):
    xRoot = findRoot(parent, x)
    yRoot = findRoot(parent, y)
 	# Attach smaller order tree under root of high order tree
    if order[xRoot] < order[yRoot]:
        parent[xRoot] = yRoot
    elif order[xRoot] > order[yRoot]:
        parent[yRoot] = xRoot
    # If orders are same, then make any one as root and increment its order by one
    else :
        parent[yRoot] = xRoot
        order[xRoot] += 1



# function that performs Kruskals algorithm on the graph G
def kruskals(G, pos):
	eLen = len(G.edges()) # eLen denotes the number of edges in G
	vLen = len(G.nodes()) # vLen denotes the number of vertices in G
	mst = [] # mst contains the MST edges
	mstFlag = {} # mstFlag[i] will hold true if the edge i has been processed for MST
	for i in [ (u, v, edata['length']) for u, v, edata in G.edges(data = True) if 'length' in edata ]:
		mstFlag[i] = False 

	parent = [None] * vLen # parent[i] will hold the vertex connected to i, in the MST
	order = [None] * vLen	# order[i] will hold the order of appearance of the node in the MST
	for v in range(vLen):
		parent[v] = v
		order[v] = 0
	while len(mst) < vLen - 1 :
		curr_edge = getMin(G, mstFlag) # pick the smallest egde from the set of edges
		mstFlag[curr_edge] = True # update the flag for the current edge
		y = findRoot(parent, curr_edge[1])
		x = findRoot(parent, curr_edge[0])
		# adds the edge to MST, if including it doesn't form a cycle
		if x != y:
			mst.append(curr_edge)
			union(parent, order, x, y)
        # Else discard the edge
    # marks the MST edges with red
	for X in mst:
	 	if (X[0], X[1]) in G.edges():
	 		nx.draw_networkx_edges(G, pos, edgelist = [(X[0], X[1])], width = 2.5, alpha = 0.6, edge_color = 'r')
	return



# takes input from the file and creates a weighted graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	wtMatrix = []
	for i in range(n):
		list1 = map(int, (f.readline()).split())
		wtMatrix.append(list1)
	# Adds egdes along with their weights to the graph 
	for i in range(n) :
		for j in range(n)[i:] :
			if wtMatrix[i][j] > 0 :
					G.add_edge(i, j, length = wtMatrix[i][j]) 
	return G



# draws the graph and displays the weights on the edges
def DrawGraph(G):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True)  # with_labels=true is to show the node number in the output graph
	edge_labels = nx.get_edge_attributes(G, 'length')
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #    prints weight on all the edges
	return pos



# main function
if __name__ == "__main__":
	G = CreateGraph()
	pos = DrawGraph(G)
	kruskals(G, pos)
	plt.show()



================================================
FILE: Prim's/README.md
================================================
# Visualisation of Prim's algorithm using networkx library

### INPUT ###


Input is taken from the file 
#### input.txt ####

Sample input
```
  5
  0 2 7 -1 -1
  2 0 3 8 5
  7 3 0 1 -1
  -1 8 1 0 4
  -1 5 -1 4 0

```
First line contains the number of nodes,say n.(Nodes are numbered as 0,1,2,...(n-1) )
Followed by n*n weighted matrix. Disconnected egdes are represented by negative weight.

### Draw Graph ###


Graph is first drawn from the weighted matrix input from the user with weights shown. Edges are marked with black.



### Prim's algorithm ###

Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for
a weighted undirected garph. 

Here, starting from an arbitrary node, the algorithm operates by building this tree one vertex at a time. At each step, smallest egde connection (also known as cut) from the tree to another vertex is added to the resulting tree.

To understand this better, consider the above input.
Let the arbitrary starting node be 0.

The graph, initially.

![1](https://user-images.githubusercontent.com/22571531/27369441-88710056-5675-11e7-8b11-251a2992b38b.png)

We use the following 3 lists:

#### dist ####
 dist[i] will hold the minimum weight edge value of node i to be included in MST(Minimum Spanning Tree).                               
#### parent ####                               
parent[i] will hold the vertex connected to i, in the MST edge.                          
#### mstSet ####                         
mstSet[i] will hold true if vertex i is included in the MST.                           

#### Initial values: ####
```
dist   = [0, inf ,inf, inf, inf]
parent = [-1, None, None, None]                        
mstSet = [True, False, False, False, False]
```

#### After the first iteration: ####

Node 1 and Node 2 form an edge with the starting node,i.e, 0 with a distance of 2 and 7 respectively. Hence they are updated accordingly.

```
dist   = [0, 2, 7, inf, inf]
parent = [-1, 0, 0, None, None] 
mstSet = [True, False, False, False, False]
```

Minimum most edge value of the nodes which are not included in the MST yet, i.e, where mstSet[i] == False, is node 1.
The node is now included in the MST, and thus, mstSet[1] is set to True.

![2](https://user-images.githubusercontent.com/22571531/27369443-8aded584-5675-11e7-9a35-a34dd3b4ba40.png)


#### After the second iteration: ####

```
dist   = [0, 2, 3, 8, 5]
parent = [-1, 0, 1, 1, 1]
mstSet = [True, True, False, False, False]
```

![3](https://user-images.githubusercontent.com/22571531/27369444-8d5e5a6e-5675-11e7-9e82-d44277d59257.png)

#### After the third iteration: ####

```
dist   = [0, 2, 3, 1, 5]
parent = [-1, 0, 1, 2, 1]
mstSet = [True, True, True, False, False]
```

![4](https://user-images.githubusercontent.com/22571531/27369448-917e86be-5675-11e7-8ecf-6d92d4e34782.png)

#### After the fourth iteration: ####

```
dist   = [0, 2, 3, 1, 4]
parent = [-1, 0, 1, 2, 3]
mstSet = [True, True, True, True, False]
```

Here, the red edges denote the Minimum Spanning Tree

![5](https://user-images.githubusercontent.com/22571531/27369450-947b6710-5675-11e7-81e3-0aff0dd4d224.png)

#### Complexity ####                                  

Time: O(V^2)                                                                 
V - Number of vertices                                                    


================================================
FILE: Prim's/input.txt
================================================
  5
  0 2 7 -1 -1
  2 0 3 8 5
  7 3 0 1 -1
  -1 8 1 0 4
  -1 5 -1 4 0

================================================
FILE: Prim's/prims.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import sys


#utility function that returns the minimum egde weight node
def minDistance(dist, mstSet, V):
   	min = sys.maxsize #assigning largest numeric value to min
   	for v in range(V):
   		if mstSet[v] == False and dist[v] < min:
   			min = dist[v]
   			min_index = v
	return min_index



#function that performs prims algorithm on the graph G
def prims(G, pos):
	V = len(G.nodes()) # V denotes the number of vertices in G
	dist = [] # dist[i] will hold the minimum weight edge value of node i to be included in MST
	parent = [None]*V # parent[i] will hold the vertex connected to i, in the MST edge
	mstSet = [] # mstSet[i] will hold true if vertex i is included in the MST
	#initially, for every node, dist[] is set to maximum value and mstSet[] is set to False
	for i in range(V):
		dist.append(sys.maxsize)
		mstSet.append(False)
	dist[0] = 0
	parent[0]= -1 #starting vertex is itself the root, and hence has no parent
	for count in range(V-1):
		u = minDistance(dist, mstSet, V) #pick the minimum distance vertex from the set of vertices
		mstSet[u] = True
		#update the vertices adjacent to the picked vertex
		for v in range(V):
			if (u, v) in G.edges():
				if mstSet[v] == False and G[u][v]['length'] < dist[v]:
					dist[v] = G[u][v]['length']
					parent[v] = u
	for X in range(V):
		if parent[X] != -1: #ignore the parent of the starting node
			if (parent[X], X) in G.edges():
				nx.draw_networkx_edges(G, pos, edgelist = [(parent[X], X)], width = 2.5, alpha = 0.6, edge_color = 'r')
	return



#takes input from the file and creates a weighted graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	wtMatrix = []
	for i in range(n):
		list1 = map(int, (f.readline()).split())
		wtMatrix.append(list1)
	#Adds egdes along with their weights to the graph 
	for i in range(n) :
		for j in range(n)[i:] :
			if wtMatrix[i][j] > 0 :
					G.add_edge(i, j, length = wtMatrix[i][j]) 
	return G



#draws the graph and displays the weights on the edges
def DrawGraph(G):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True)  #with_labels=true is to show the node number in the output graph
	edge_labels = nx.get_edge_attributes(G,'length')
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
	return pos



#main function
if __name__ == "__main__":
	G = CreateGraph()
	pos = DrawGraph(G)
	prims(G, pos)
	plt.show()



================================================
FILE: README.md
================================================
# Visualization-of-popular-algorithms-in-Python

### Description

The project aims to create visual outputs for popular graph algorithms like DFS,BFS and NP-HARD problems like Travelling Salesman Problem and Graph colouring problems using NetworkX graph library of Python. It is not just limited to getting a visual output, but the algorithms will be optimised to its best by using heuristics for non-polynomial time algorithms. The project aims to create a better understanding of the working of the algorithms, in-depth understanding of the application of heuristics to improve the computation time and usage of the later to our advantage in optimising the algorithm. It could be used by analysts as well as students and teachers, as a teaching aid. It could definitely serve all the applications of Np-hard problems like- School scheduling, Tourist Itineraries, etc.

### Motivation

DFS,BFS and NP-Hard algorithms have been there for years now and it has been coded out in every programming language as well. This project aims in visulization of them, to create a better understanding. Solving most of the above mentioned algorithm using brute force-technique might give the optimal solution, however, as the problem size increases, the search for an optimal solution will no longer be worth the effort. Hence, by involving heuristics, we aim to improve the time complexity while arriving at a good solution( need not be optimal always). (Heuristics is used, to predict how close the end of path is to a solution, so that the paths which are judged to be closer to a solution are extended first.)

It includes:
### 1. DFS:
[DFS](/DFS)
### 2. BFS:
[BFS](/BFS)
### 3. Dijsktra's:
[Dijsktra's](/Dijsktra's)
### 4. Prim's:
[Prim's](/Prim's)
### 5. Kruskal's:
[Kruskal's](/Kruskal's)
### 6. Assignment Problem:
[Assignment Problem](/Assignment%20Problem)
### 7. Travelling Salesman Problem:
[Travelling Salesman Problem](/Travelling%20Salesman%20Problem)
### 8. Greedy Best First Search:
[Greedy BFS](/Greedy%20BFS)
### 9. A* Search:
[A* Search](/A_star_search)
### 10. Topological Sort:
[Topological Sort](/Topological%20Sort)
### 11. Graph Coloring Problem:
[Graph-Coloring Problem](/Graph%20Coloring)
### 12. K Centers Problem:
[K Centers Problem](/K%20Centers%20Problem)
### 13. Egocentric Network:
[Egocentric Network](/Egocentric%20Network)
### 14. Bellman-Ford algorithm:
[Bellman Ford](/BellmanFord)


================================================
FILE: Topological Sort/README.md
================================================
# Visualisation of Topological sort algorithm using networkx library

### Topological sort ###

 Topological sort of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks.
 PS: Topological sorting is possible only if the graph is a directed acyclic graph.

 Two commom approaches for topological sort:
 1. Kahn's algorithm
 2. Depth - first search

 The code here is an implementation of Kahn's algorithm.

 #### Kahn's algorithm ####

 This is computationally simpler compared to DFS approach.

 Step 1: Find all the nodes in the graph with in-degree as 0 and add them into a queue
 Step 2: Remove the nodes from the queue one by one, append it to the sorted_list and simulatneously update the graph(remove the node from the graph, resulting which, in-degree of nodes which had edges directed from the reomved node decreases by one).
 Step 3: If there are anymore nodes left in the graph, go back to step 1 

 This method is optimal but modifies the graph. For the algorithm to not modify the original graph, you'll need to maintain a boolean array visited[] - to keep track to the visited nodes and indegree[] to store the in-degree of the graph nodes.

#### Working ####

Consider the sample input below:

```
6
1 2
1 3
2 3
2 4
3 4
3 5
```
Visualization of the input graph:

![1](https://user-images.githubusercontent.com/22571531/27983933-e09f086c-63e6-11e7-9830-b63a48b829b6.png)


Node 1 is the only node with in-degree as 0.
Remove it from the graph, and append it to the sorted_list.
sorted_list = [1]

Now, Node 2 has an in-degree of 0. Remove it from the graph, and append it to the sorted list.
sorted_list = [1,2]

Next, Node 3 has an in-degree of 0. 
sorted_list = [1,2 3]

Next, Node 4 and Node 5, both have an in-degree of 0.
sorted_list = [1,2,3,4,5]
Note that: [1,2,3,5,4] is also the right order.

Visualization of the topologically sorted order.                              
Green node - denotes the starting node.                                      
Red node - denotes the final node.

![2](https://user-images.githubusercontent.com/22571531/27983935-e5d92286-63e6-11e7-92f3-e45c9bbb6039.png)                                                                             


 





================================================
FILE: Topological Sort/input.txt
================================================
6
1 2
1 3
2 3
2 4
3 4
3 5


================================================
FILE: Topological Sort/topological_sort.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
 

def topologicalSort(G,pos):
	zero_indeg_list = [] 
	sorted_list = []
	visited = [False]*len(G.nodes())
	while len(G.nodes())!=0:
		for node in G.nodes():
			if visited[node-1] == False:
				if G.in_degree(node) == 0:
					visited[node-1] = True
					zero_indeg_list.append(node)
		for node in zero_indeg_list:
			sorted_list.append(node)
			G.remove_node(node)
			zero_indeg_list.remove(node)
	return sorted_list

		
#takes input from the file and creates a directed graph
def CreateResultGraph(sorted_list):
	D = nx.DiGraph()
	for i in range(len(sorted_list)-1): 
	 	D.add_edge(sorted_list[i], sorted_list[i+1]) 
	pos = nx.spring_layout(D)
	val_map = {}
	val_map[sorted_list[0]] = 'green'
	val_map[sorted_list[len(sorted_list)-1]] = 'red'
	values = [val_map.get(node, 'blue') for node in D.nodes()]
	nx.draw(D, pos, with_labels = True, node_color =values)
	

#takes input from the file and creates a directed graph
def CreateGraph():
	G = nx.DiGraph()
	f = open('input.txt')
	n = int(f.readline())
	for i in range(n):
		adj_list = map(int, (f.readline()).split()) 
		G.add_edge(adj_list[0], adj_list[1]) 
	return G



#draws the graph
def DrawGraph(G):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True, node_color ='blue')  #with_labels=true is to show the node number in the output graph
	return pos



#main function
if __name__== "__main__":
	G = CreateGraph()
	plt.figure(1)
	pos = DrawGraph(G)
	plt.figure(2)
	sorted_list = topologicalSort(G,pos)
	CreateResultGraph(sorted_list)
	plt.show()



================================================
FILE: Travelling Salesman Problem/README.md
================================================
# Visualisation of Travelling Salesman Problem using networkx library

### Travelling Salesman Problem ###

Travelling salesman problem is a NP hard problem. Given a set of cities and the distance between every pair of cities, the problem is to find the shortest possible route that visits each city exactly once and returns back to the original city. Hence, it also belongs to the class of optimization problems. 

#### Why NP-hard?

First, let us understand the definition of NP- hard.
NP (nondeterministic polynomial time) problem is the one whose solution could be verified in polynomial time but the problem is not guaranteed to be solved in polynomial time.
Now, NP - hard problem are those which are atleast as hard as any NP problem.
NP complete problem is the class of problems that are both NP and NP-hard.

Let us now check both the conditions.

 ##### condition (i): NP
  To check that given solution is the right solution for a TSP problem. We need to verify two things:
  Firstly, each city must be visited exactly once. (could be done in polynomial time)
  Secondly, there is no shorter route than the current solution. (This cannot be guaranteed in polynomial time)
  Hence, TSP is not NP

 ##### condition (ii): NP hard
 Surely TSP is a NP hard problem. (For, even it's solution can't be guaranteed in polynomial time)

 Thus, TSP belongs to the class of NP-hard problem and not NP-complete.


Brute force approach for TSP will need all possible paths to be calculated which is (n-1)! paths( where n is the number of cities). As n increases, it is computationally not feasible to compute that many paths.

There are certain approximation algorithms for TSP which guarantees to solve the problem in polynomial time at the cost of solution not being exact. Christofides algorithm, is one such heuristics approach which guarantees it's solution to be within a factor of 1.5 of the optimal solution. By far, Christofides algorithm (time complexity : O(n^3)) is known to have the best approximation ratio for a general TSP problem. 

#### Christofides algorithm:

1. Create a minimum spanning tree MST of G. (using Kruskal's or Prim's algorithm)
2. Let odd_vert be the set of vertices with odd degree in MST. The number of vertices with odd_degree is guaranteed to be even( Proof: Handshaking Lemma).
3. Find a minimum-weight perfect matching pairs in the induced subgraph given by the vertices from odd_vert. Add those edges to MST.
 The resulting MST now has all the vertices with even degree- hence, is a Eulerian circuit.
4. Make the circuit found in previous step into a Hamiltonian circuit by skipping repeated vertices.

The code here,is an implementation of Christofides algorithm. 

### INPUT ###


Input is taken from the file 
#### input.txt ####

Sample input
```
5
0 10 8 9 7
10 0 10 5 6
8 10 0 8 9
9 5 8 0 6
7 6 9 6 0

```
First line contains n, the number of cities.
Followed by n*n distance matrix where matrix[i][j] denotes the distance between city i and city j.


### Draw Graph ###


An undireced graph is drawn with nodes representing the cities and egde labels denoting the distance between them.

![screenshot from 2017-06-29 12-50-58](https://user-images.githubusercontent.com/22571531/27676532-f2af862a-5ccb-11e7-9ba3-8a9cb87adca9.png)

Step 1:

A minimum spanning tree MST is obtained from the given grapg G (using Kruskal's algorithm)

![screenshot from 2017-06-29 12-53-47](https://user-images.githubusercontent.com/22571531/27676537-f787e962-5ccb-11e7-8da7-e48e223d33a8.png)

Step 2:

There are 2 vertices with odd degree in MST graph, that is, node 2 and node 3.
Hence, odd_vert = [2,3]

Step 3:

Since there are only 2 vertices in odd_vert, we get one minimum weight matching pair, i,e, (2,3). Adding this edge to MST, we have the below graph.

![screenshot from 2017-06-29 12-48-48](https://user-images.githubusercontent.com/22571531/27676543-fb8d0d76-5ccb-11e7-93b9-bc7d6767b24d.png)


Step 4:

Finding the shortest hamiltonian circuit from the above graph (by skipping already visisted vertices) , we have
```
0 -> 2 -> 3 -> 1 -> 4 -> 0
```

The below diagram shows the shortest route for TSP. 
PS: The arrows here are just for visual purposes to denote the route. The cycle could be traversed in any direction.

![second](https://user-images.githubusercontent.com/22571531/27676549-01632fc8-5ccc-11e7-964e-eece9960b4b8.png)

#### Complexity ####

Time: O(n^3)                                                          
n - number of Nodes

================================================
FILE: Travelling Salesman Problem/input.txt
================================================
5
0 10 8 9 7
10 0 10 5 6
8 10 0 8 9
9 5 8 0 6
7 6 9 6 0

================================================
FILE: Travelling Salesman Problem/tsp_christofides.py
================================================
import networkx as nx
import matplotlib.pyplot as plt
import sys

# A utility function that return the smallest unprocessed edge
def getMin(G, mstFlag):
    min = sys.maxsize  # assigning largest numeric value to min
    for i in [(u, v, edata['length']) for u, v, edata in G.edges( data = True) if 'length' in edata ]:
    	if mstFlag[i] == False and i[2] < min:
    		min = i[2]
    		min_edge = i
    return min_edge

# A utility function to find root or origin of the node i in MST
def findRoot(parent, i):
    if parent[i] == i:
        return i
    return findRoot(parent, parent[i])


# A function that does union of set x and y based on the order
def union(parent, order, x, y):
    xRoot = findRoot(parent, x)
    yRoot = findRoot(parent, y)
 	# Attach smaller order tree under root of high order tree
    if order[xRoot] < order[yRoot]:
        parent[xRoot] = yRoot
    elif order[xRoot] > order[yRoot]:
        parent[yRoot] = xRoot
    # If orders are same, then make any one as root and increment its order by one
    else :
        parent[yRoot] = xRoot
        order[xRoot] += 1

#function that performs kruskals algorithm on the graph G	
def genMinimumSpanningTree(G):
	MST = nx.Graph()
	eLen = len(G.edges()) # eLen denotes the number of edges in G
	vLen = len(G.nodes()) # vLen denotes the number of vertices in G
	mst = [] # mst contains the MST edges
	mstFlag = {} # mstFlag[i] will hold true if the edge i has been processed for MST
	for i in [ (u, v, edata['length']) for u, v, edata in G.edges(data = True) if 'length' in edata ]:
		mstFlag[i] = False 

	parent = [None] * vLen # parent[i] will hold the vertex connected to i, in the MST
	order = [None] * vLen	# order[i] will hold the order of appearance of the node in the MST
	for v in range(vLen):
		parent[v] = v
		order[v] = 0
	while len(mst) < vLen - 1 :
		curr_edge = getMin(G, mstFlag) # pick the smallest egde from the set of edges
		mstFlag[curr_edge] = True # update the flag for the current edge
		y = findRoot(parent, curr_edge[1])
		x = findRoot(parent, curr_edge[0])
		# adds the edge to MST, if including it doesn't form a cycle
		if x != y:
			mst.append(curr_edge)
			union(parent, order, x, y)
        # Else discard the edge
	for X in mst:
		if (X[0], X[1]) in G.edges(): 
				MST.add_edge(X[0], X[1], length = G[X[0]][X[1]]['length']) 
	return MST


#utility function that adds minimum weight matching edges to MST
def minimumWeightedMatching(MST, G, odd_vert):
	while odd_vert:
		v = odd_vert.pop()
		length = float("inf")
		u = 1
		closest = 0
		for u in odd_vert:
			if G[v][u]['length'] < length :
				length = G[v][u]['length']
				closest = u
		MST.add_edge(v, closest, length = length)
		odd_vert.remove(closest)
  



def christofedes(G ,pos):
	opGraph=nx.DiGraph()
	#optimal_dist = 0
	MST = genMinimumSpanningTree(G) # generates minimum spanning tree of graph G, using Prim's algo
	odd_vert = [] #list containing vertices with odd degree
	for i in MST.nodes():
		if MST.degree(i)%2 != 0: 
			odd_vert.append(i) #if the degree of the vertex is odd, then append it to odd_vert list
	minimumWeightedMatching(MST, G, odd_vert) #adds minimum weight matching edges to MST
	# now MST has the Eulerian circuit
	start = MST.nodes()[0]
	visited = [False] * len(MST.nodes())
	# finds the hamiltonian circuit
	curr = start
	visited[curr] = True
	for nd in MST.neighbors(curr):
			if visited[nd] == False or nd == start:
				next = nd
				break
	while next != start:
		visited[next]=True
		opGraph.add_edge(curr,next,length = G[curr][next]['length'])
		nx.draw_networkx_edges(G, pos, arrows = True, edgelist = [(curr, next)], width = 2.5, alpha = 0.6, edge_color = 'r')
		# optimal_dist = optimal_dist + G[curr][next]['length']
		# finding the shortest Eulerian path from MST
		curr = next
		for nd in MST.neighbors(curr):
			if visited[nd] == False:
				next = nd
				break
		if next == curr:
			for nd in G.neighbors(curr):
				if visited[nd] == False:
					next = nd
					break
		if next == curr:
			next = start
	opGraph.add_edge(curr,next,length = G[curr][next]['length'])
	nx.draw_networkx_edges(G, pos, edgelist = [(curr, next)], width = 2.5, alpha = 0.6, edge_color = 'r')
	# optimal_dist = optimal_dist + G[curr][next]['length']
	# print optimal_dist
	return opGraph




	
#takes input from the file and creates a weighted undirected graph
def CreateGraph():
	G = nx.Graph()
	f = open('input.txt')
	n = int(f.readline())
	wtMatrix = []
	for i in range(n):
		list1 = map(int, (f.readline()).split())
		wtMatrix.append(list1)
	#Adds egdes along with their weights to the graph 
	for i in range(n) :
		for j in range(n)[i:] :
			if wtMatrix[i][j] > 0 :
					G.add_edge(i, j, length = wtMatrix[i][j]) 
	return G

def DrawGraph(G,color):
	pos = nx.spring_layout(G)
	nx.draw(G, pos, with_labels = True, edge_color = color)  #with_labels=true is to show the node number in the output graph
	edge_labels = nx.get_edge_attributes(G,'length')
	nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels,  font_size = 11) #prints weight on all the edges
	return pos


#main function
if __name__ == "__main__":
	G = CreateGraph()
	plt.figure(1)
	pos = DrawGraph(G,'black')
	opGraph = christofedes(G, pos)
	plt.figure(2)
	pos1 = DrawGraph(opGraph,'r') 
	plt.show()

================================================
FILE: setup.sh
================================================
#!/bin/bash
if [ $(uname -s) == "Linux" ]; then
  declare -a distributions=("Manjaro" "Ubuntu" "Arch");
  declare -a distpackagemgrs=("1" "0" "1");
  declare -a packagemgr=("apt-get" "pacman");

  dist_count=${#distributions[*]}
  usable_mgr="-1"

  dist_name=$(lsb_release -a);

  for (( i=0; i<=$(( $dist_count -1 )); i++ ))
  do
      if [ $(echo "$dist_name" | grep -c "${distributions[$i]}") -gt 0 ]; then
          usable_mgr=${distpackagemgrs[$i]}
          echo "Found Distribution ${distributions[$i]}, will use ${packagemgr[usable_mgr]}"
      fi
  done

  if [ $usable_mgr == "-1" ]; then
      echo "Err: Linux distibution unknown, will use apt-get"
      usable_mgr="0"
  fi

  case $usable_mgr in
      "0")
      echo "-- apt-get install --"
      sudo apt-get install python2.7-dev python-pip -y

      ;;
      "1")
      echo "-- pacman installation --"
      sudo pacman -S python2 python-pip -y

      ;;
  esac
fi

if [ $(uname -s) == "Darwin" ]; then
  sudo easy_install pip

fi

sudo pip2 install matplotlib
sudo pip2 install networkx




Download .txt
gitextract_rqk1_unp/

├── A_star_search/
│   ├── README.md
│   ├── a_star_search.py
│   ├── heuristics.txt
│   └── input.txt
├── Assignment Problem/
│   ├── README.md
│   ├── assignment_prob_hungarian.py
│   └── input.txt
├── BFS/
│   ├── README.md
│   ├── bfs.py
│   └── input.txt
├── BellmanFord/
│   ├── BellmanFord.py
│   └── input.txt
├── DFS/
│   ├── README.md
│   ├── dfs_visual.py
│   └── input.txt
├── Dijsktra's/
│   ├── README.md
│   ├── dijsktras.py
│   └── input.txt
├── Egocentric Network/
│   ├── egocentric_network_1.py
│   ├── egocentric_network_1_5.py
│   ├── egocentric_network_2.py
│   └── input.txt
├── Graph Coloring/
│   ├── README.md
│   ├── graph_coloring.py
│   └── input.txt
├── Greedy BFS/
│   ├── README.md
│   ├── greedy_bfs.py
│   ├── heuristics.txt
│   └── input.txt
├── K Centers Problem/
│   ├── README.md
│   ├── input.txt
│   └── k_centers_problem.py
├── Kruskal's/
│   ├── README.md
│   ├── input.txt
│   └── kruskals_quick_union.py
├── Prim's/
│   ├── README.md
│   ├── input.txt
│   └── prims.py
├── README.md
├── Topological Sort/
│   ├── README.md
│   ├── input.txt
│   └── topological_sort.py
├── Travelling Salesman Problem/
│   ├── README.md
│   ├── input.txt
│   └── tsp_christofides.py
└── setup.sh
Download .txt
SYMBOL INDEX (80 symbols across 16 files)

FILE: A_star_search/a_star_search.py
  function getPriorityQueue (line 7) | def getPriorityQueue(G, v):
  function aStarSearchUtil (line 15) | def aStarSearchUtil(G, v, visited, final_path, dest, goal):
  function aStarSearch (line 36) | def aStarSearch(G, source, dest, heuristics, pos):
  class Ordered_Node (line 54) | class Ordered_Node(object):
    method __init__ (line 55) | def __init__(self, priority, description):
    method __cmp__ (line 59) | def __cmp__(self, other):
  function getHeuristics (line 62) | def getHeuristics(G):
  function CreateGraph (line 73) | def CreateGraph():
  function DrawPath (line 85) | def DrawPath(G, source, dest):

FILE: Assignment Problem/assignment_prob_hungarian.py
  function init_labels (line 8) | def init_labels(cost):
  function update_labels (line 19) | def update_labels(T, slack, S, lx, ly, n):
  function add_to_tree (line 36) | def add_to_tree(x, prevx, S, prev, lx, ly, slack, slackx, cost):
  function augment (line 47) | def augment(cost, max_match, xy, yx, lx, ly, slack, slackx):
  function hungarian (line 123) | def hungarian(B ,pos ,cost):
  function CreateGraph (line 140) | def CreateGraph():
  function DrawGraph (line 165) | def DrawGraph(B):

FILE: BFS/bfs.py
  function BFS (line 7) | def BFS(G, source, pos):
  function CreateGraph (line 24) | def CreateGraph():
  function DrawGraph (line 43) | def DrawGraph(G):

FILE: BellmanFord/BellmanFord.py
  function bellmanFord (line 8) | def bellmanFord(G, source, pos):
  function createGraph (line 33) | def createGraph():
  function DrawGraph (line 51) | def DrawGraph(G):

FILE: DFS/dfs_visual.py
  function DFSUtil (line 7) | def DFSUtil(G, v, visited, sl):
  function DFS (line 18) | def DFS(G, source):
  function CreateGraph (line 32) | def CreateGraph():
  function DrawDFSPath (line 51) | def DrawDFSPath(G, dfs_stk):

FILE: Dijsktra's/dijsktras.py
  function minDistance (line 8) | def minDistance(dist, sptSet, V):
  function dijsktras (line 19) | def dijsktras(G, source, pos):
  function CreateGraph (line 49) | def CreateGraph():
  function DrawGraph (line 68) | def DrawGraph(G):

FILE: Egocentric Network/egocentric_network_1.py
  function EgocentricNetwork (line 5) | def EgocentricNetwork(G,v):
  function CreateGraph (line 16) | def CreateGraph():
  function DrawGraph (line 32) | def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_lis...
  function CentralityMeasures (line 41) | def CentralityMeasures(G):

FILE: Egocentric Network/egocentric_network_1_5.py
  function EgocentricNetwork (line 6) | def EgocentricNetwork(G,v):
  function CreateGraph (line 25) | def CreateGraph():
  function DrawGraph (line 41) | def DrawGraph(G, egocentric_network_edge_list, egocentric_network_node_l...
  function CentralityMeasures (line 50) | def CentralityMeasures(G):

FILE: Egocentric Network/egocentric_network_2.py
  function EgocentricNetwork (line 6) | def EgocentricNetwork(G,v):
  function CreateGraph (line 39) | def CreateGraph():
  function DrawGraph (line 55) | def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list):
  function DrawGraph (line 63) | def DrawGraph(G, egocentric_network_edge_list, egocentric_network_node_l...
  function CentralityMeasures (line 72) | def CentralityMeasures(G):

FILE: Graph Coloring/graph_coloring.py
  function welsh_powell (line 6) | def welsh_powell(G):
  function CreateGraph (line 33) | def CreateGraph():
  function DrawGraph (line 44) | def DrawGraph(G,col_val):

FILE: Greedy BFS/greedy_bfs.py
  function getPriorityQueue (line 7) | def getPriorityQueue(list):
  function greedyBFSUtil (line 15) | def greedyBFSUtil(G, v, visited, final_path, dest, goal):
  function greedyBFS (line 36) | def greedyBFS(G, source, dest, heuristics, pos):
  class Ordered_Node (line 54) | class Ordered_Node(object):
    method __init__ (line 55) | def __init__(self, priority, description):
    method __cmp__ (line 59) | def __cmp__(self, other):
  function getHeuristics (line 62) | def getHeuristics(G):
  function CreateGraph (line 73) | def CreateGraph():
  function DrawPath (line 85) | def DrawPath(G, source, dest):

FILE: K Centers Problem/k_centers_problem.py
  function k_centers (line 7) | def k_centers(G, n):
  function CreateGraph (line 34) | def CreateGraph():
  function DrawGraph (line 52) | def DrawGraph(G, centers):

FILE: Kruskal's/kruskals_quick_union.py
  function getMin (line 8) | def getMin(G, mstFlag):
  function findRoot (line 19) | def findRoot(parent, i):
  function union (line 27) | def union(parent, order, x, y):
  function kruskals (line 43) | def kruskals(G, pos):
  function CreateGraph (line 75) | def CreateGraph():
  function DrawGraph (line 93) | def DrawGraph(G):

FILE: Prim's/prims.py
  function minDistance (line 7) | def minDistance(dist, mstSet, V):
  function prims (line 18) | def prims(G, pos):
  function CreateGraph (line 47) | def CreateGraph():
  function DrawGraph (line 65) | def DrawGraph(G):

FILE: Topological Sort/topological_sort.py
  function topologicalSort (line 5) | def topologicalSort(G,pos):
  function CreateResultGraph (line 23) | def CreateResultGraph(sorted_list):
  function CreateGraph (line 36) | def CreateGraph():
  function DrawGraph (line 48) | def DrawGraph(G):

FILE: Travelling Salesman Problem/tsp_christofides.py
  function getMin (line 6) | def getMin(G, mstFlag):
  function findRoot (line 15) | def findRoot(parent, i):
  function union (line 22) | def union(parent, order, x, y):
  function genMinimumSpanningTree (line 36) | def genMinimumSpanningTree(G):
  function minimumWeightedMatching (line 67) | def minimumWeightedMatching(MST, G, odd_vert):
  function christofedes (line 83) | def christofedes(G ,pos):
  function CreateGraph (line 131) | def CreateGraph():
  function DrawGraph (line 146) | def DrawGraph(G,color):
Condensed preview — 46 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (87K chars).
[
  {
    "path": "A_star_search/README.md",
    "chars": 3463,
    "preview": "# Visualisation of A* Search using networkx library\n\n### A* Search ###\n\nA* search( pronounced as \"A star\") is a search a"
  },
  {
    "path": "A_star_search/a_star_search.py",
    "chars": 2674,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport Queue as Q\n \n \n\ndef getPriorityQueue(G, v):\n\tq = Q.Priority"
  },
  {
    "path": "A_star_search/heuristics.txt",
    "chars": 230,
    "preview": "Arad 366\nBucharest 0\nCraiova 160\nDobreta 242\nEforie 161\nFagaras 178\nGiurgiu 77\nHirsova 151\nIasi 226\nLugoj 244\nMehadia 24"
  },
  {
    "path": "A_star_search/input.txt",
    "chars": 464,
    "preview": "23\nArad Sibiu 140\nArad Timisoara 118\nArad Zerind 75\nBucharest Fagaras 211\nBucharest Giurgiu 90\nBucharest Pitesti 101\nBuc"
  },
  {
    "path": "Assignment Problem/README.md",
    "chars": 1682,
    "preview": "# Visualisation of Assignment Problem using networkx library\n\n### INPUT ###\n\n\nInput is taken from the file \n#### input.t"
  },
  {
    "path": "Assignment Problem/assignment_prob_hungarian.py",
    "chars": 3966,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nfrom networkx.algorithms import bipartite\nfrom string import ascii"
  },
  {
    "path": "Assignment Problem/input.txt",
    "chars": 34,
    "preview": "4\n9 2 7 8\n6 4 3 7 \n5 8 1 8\n7 6 9 4"
  },
  {
    "path": "BFS/README.md",
    "chars": 1381,
    "preview": "# Visualisation of BFS traversal using networkx library\n\n### INPUT ###\n\n\nInput is taken from the file \n#### input.txt ##"
  },
  {
    "path": "BFS/bfs.py",
    "chars": 1621,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\n \n\n\n#BFS traversal \ndef BFS(G, source, pos): \n\tvisited = [False]*("
  },
  {
    "path": "BFS/input.txt",
    "chars": 39,
    "preview": "4\n0 5 10 5\n0 0 5 0\n0 10 0 0\n0 0 10 0\n0\n"
  },
  {
    "path": "BellmanFord/BellmanFord.py",
    "chars": 2391,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport sys\n\ninf = float('inf')\n\n#function that performs Bellman-Fo"
  },
  {
    "path": "BellmanFord/input.txt",
    "chars": 65,
    "preview": "5\n0 2 7 -1 -1\n-1 0 3 8 5\n-1 2 0 1 -1\n-1 -1 -1 0 4\n-1 -1 -1 5 0\n0\n"
  },
  {
    "path": "DFS/README.md",
    "chars": 1413,
    "preview": "# Visualisation of DFS traversal using networkx library\n\n### INPUT ###\n\nGraph is first drawn from the weighted matrix in"
  },
  {
    "path": "DFS/dfs_visual.py",
    "chars": 2322,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\n \n\n\n#utility fucntion used by DFS which does recursive depth first"
  },
  {
    "path": "DFS/input.txt",
    "chars": 36,
    "preview": "4\n0 5 0 5\n5 0 5 0\n0 5 0 5\n5 0 5 0\n0\n"
  },
  {
    "path": "Dijsktra's/README.md",
    "chars": 3268,
    "preview": "# Visualisation of Dijsktra's algorithm using networkx library\n\n### INPUT ###\n\n\nInput is taken from the file \n#### input"
  },
  {
    "path": "Dijsktra's/dijsktras.py",
    "chars": 2816,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport sys\n \n\n\n#utility function that returns the minimum distance"
  },
  {
    "path": "Dijsktra's/input.txt",
    "chars": 80,
    "preview": "  5\n  0 2 7 -1 -1\n  -1 0 3 8 5\n  -1 2 0 1 -1\n  -1 -1 -1 0 4\n  -1 -1 -1 5 0\n  0\n\n"
  },
  {
    "path": "Egocentric Network/egocentric_network_1.py",
    "chars": 2119,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\n \n\ndef EgocentricNetwork(G,v):\n\tegocentric_network_edge_list = []\n"
  },
  {
    "path": "Egocentric Network/egocentric_network_1_5.py",
    "chars": 2491,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport itertools\n \n\ndef EgocentricNetwork(G,v):\n\t\n\tegocentric_netw"
  },
  {
    "path": "Egocentric Network/egocentric_network_2.py",
    "chars": 3496,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport itertools\n \n\ndef EgocentricNetwork(G,v):\n\t\n\tegocentric_netw"
  },
  {
    "path": "Egocentric Network/input.txt",
    "chars": 51,
    "preview": "10\n11\n1 2\n1 4\n1 3\n3 9\n3 6\n6 8\n8 9\n6 9\n4 6\n4 5\n5 7\n9"
  },
  {
    "path": "Graph Coloring/README.md",
    "chars": 2254,
    "preview": "# Visualisation of Graph Coloring Problem using networkx library\n\n### Graph Coloring ###\n\n Graph Coloring Problem is an "
  },
  {
    "path": "Graph Coloring/graph_coloring.py",
    "chars": 1660,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\n\n\n#implementation of welsh_powell algorithm\ndef welsh_powell(G):\n\t"
  },
  {
    "path": "Graph Coloring/input.txt",
    "chars": 71,
    "preview": "16\n0 7\n0 1\n1 3\n3 2\n3 8\n3 10\n7 8\n7 9\n7 10\n7 6\n8 9\n9 10\n6 5\n10 4\n5 4\n6 10"
  },
  {
    "path": "Greedy BFS/README.md",
    "chars": 3799,
    "preview": "\n\n# Visualisation of Greedy BFS using networkx library\n\n### Greedy Best First Search ###\n\nBest-first search is a search "
  },
  {
    "path": "Greedy BFS/greedy_bfs.py",
    "chars": 2630,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport Queue as Q\n \n \n\ndef getPriorityQueue(list):\n\tq = Q.Priority"
  },
  {
    "path": "Greedy BFS/heuristics.txt",
    "chars": 230,
    "preview": "Arad 366\nBucharest 0\nCraiova 160\nDobreta 242\nEforie 161\nFagaras 178\nGiurgiu 77\nHirsova 151\nIasi 226\nLugoj 244\nMehadia 24"
  },
  {
    "path": "Greedy BFS/input.txt",
    "chars": 464,
    "preview": "23\nArad Sibiu 140\nArad Timisoara 118\nArad Zerind 75\nBucharest Fagaras 211\nBucharest Giurgiu 90\nBucharest Pitesti 101\nBuc"
  },
  {
    "path": "K Centers Problem/README.md",
    "chars": 2228,
    "preview": "# Visualisation of K - Centers Problem using networkx library\n\n### K - Center ###\n\n K - Center problem (also known as Me"
  },
  {
    "path": "K Centers Problem/input.txt",
    "chars": 39,
    "preview": "4\n0 10 7 6\n10 0 8 5\n7 8 0 12\n6 5 12 0\n2"
  },
  {
    "path": "K Centers Problem/k_centers_problem.py",
    "chars": 1875,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport operator\n\n\n\ndef k_centers(G, n):\n\tcenters = []\n\tcities = G."
  },
  {
    "path": "Kruskal's/README.md",
    "chars": 2572,
    "preview": "# Visualisation of Kruskal's algorithm using networkx library\n\n### INPUT ###\n\n\nInput is taken from the file \n#### input."
  },
  {
    "path": "Kruskal's/input.txt",
    "chars": 69,
    "preview": "  5\n  0 2 7 -1 -1\n  2 0 3 8 5\n  7 3 0 1 -1\n  -1 8 1 0 4\n  -1 5 -1 4 0"
  },
  {
    "path": "Kruskal's/kruskals_quick_union.py",
    "chars": 3331,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport sys\n\n\n\n# A utility function that return the smallest unproc"
  },
  {
    "path": "Prim's/README.md",
    "chars": 3342,
    "preview": "# Visualisation of Prim's algorithm using networkx library\n\n### INPUT ###\n\n\nInput is taken from the file \n#### input.txt"
  },
  {
    "path": "Prim's/input.txt",
    "chars": 69,
    "preview": "  5\n  0 2 7 -1 -1\n  2 0 3 8 5\n  7 3 0 1 -1\n  -1 8 1 0 4\n  -1 5 -1 4 0"
  },
  {
    "path": "Prim's/prims.py",
    "chars": 2491,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport sys\n\n\n#utility function that returns the minimum egde weigh"
  },
  {
    "path": "README.md",
    "chars": 2407,
    "preview": "# Visualization-of-popular-algorithms-in-Python\n\n### Description\n\nThe project aims to create visual outputs for popular "
  },
  {
    "path": "Topological Sort/README.md",
    "chars": 2546,
    "preview": "# Visualisation of Topological sort algorithm using networkx library\n\n### Topological sort ###\n\n Topological sort of a d"
  },
  {
    "path": "Topological Sort/input.txt",
    "chars": 26,
    "preview": "6\n1 2\n1 3\n2 3\n2 4\n3 4\n3 5\n"
  },
  {
    "path": "Topological Sort/topological_sort.py",
    "chars": 1569,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\n \n\ndef topologicalSort(G,pos):\n\tzero_indeg_list = [] \n\tsorted_list"
  },
  {
    "path": "Travelling Salesman Problem/README.md",
    "chars": 4484,
    "preview": "# Visualisation of Travelling Salesman Problem using networkx library\n\n### Travelling Salesman Problem ###\n\nTravelling s"
  },
  {
    "path": "Travelling Salesman Problem/input.txt",
    "chars": 55,
    "preview": "5\n0 10 8 9 7\n10 0 10 5 6\n8 10 0 8 9\n9 5 8 0 6\n7 6 9 6 0"
  },
  {
    "path": "Travelling Salesman Problem/tsp_christofides.py",
    "chars": 5256,
    "preview": "import networkx as nx\nimport matplotlib.pyplot as plt\nimport sys\n\n# A utility function that return the smallest unproces"
  },
  {
    "path": "setup.sh",
    "chars": 1062,
    "preview": "#!/bin/bash\nif [ $(uname -s) == \"Linux\" ]; then\n  declare -a distributions=(\"Manjaro\" \"Ubuntu\" \"Arch\");\n  declare -a dis"
  }
]

About this extraction

This page contains the full source code of the MUSoC/Visualization-of-popular-algorithms-in-Python GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 46 files (78.7 KB), approximately 24.3k tokens, and a symbol index with 80 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!