filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/graph_algorithms/src/floyd_warshall_algorithm/floyd_warshall_algorithm.py | """ Part of Cosmos by OpenGenus Foundation """
INF = 1000000000
def floyd_warshall(vertex, adjacency_matrix):
# calculating all pair shortest path
for k in range(0, vertex):
for i in range(0, vertex):
for j in range(0, vertex):
# relax the distance from i to j by allowing vertex k as intermediate vertex
# consider which one is better, going through vertex k or the previous value
adjacency_matrix[i][j] = min(
adjacency_matrix[i][j],
adjacency_matrix[i][k] + adjacency_matrix[k][j],
)
# pretty print the graph
# o/d means the leftmost row is the origin vertex
# and the topmost column as destination vertex
print("o/d", end="")
for i in range(0, vertex):
print("\t{:d}".format(i + 1), end="")
print()
for i in range(0, vertex):
print("{:d}".format(i + 1), end="")
for j in range(0, vertex):
print("\t{:d}".format(adjacency_matrix[i][j]), end="")
print()
"""
input is given as adjacency matrix,
input represents this undirected graph
A--1--B
| /
3 /
| 1
| /
C--2--D
should set infinite value for each pair of vertex that has no edge
"""
adjacency_matrix = [[0, 1, 3, INF], [1, 0, 1, INF], [3, 1, 0, 2], [INF, INF, 2, 0]]
floyd_warshall(4, adjacency_matrix)
|
code/graph_algorithms/src/ford_fulkerson_maximum_flow/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <string.h>
using namespace std;
#define N 7
#define INF 9999999
// flow network
int Flow[N][N];
// visited array
bool visited[N];
// original flow network graph shown in the above example
//0 1 2 3 4 5 6
int graph[N][N] = {
{ 0, 5, 4, 0, 0, 0, 0 }, //0
{ 0, 0, 0, 0, 0, 0, 4 }, //1
{ 0, 0, 0, 3, 0, 0, 6 }, //2
{ 0, 0, 0, 0, 5, 0, 0 }, //3
{ 0, 0, 0, 0, 0, 0, 8 }, //4
{ 6, 0, 0, 2, 0, 0, 0 }, //5
{ 0, 0, 0, 0, 0, 0, 0 }, //6
};
int dfs(int s, int t, int minimum)
{
visited[s] = true;
// if source and sink is same
if (s == t)
return minimum;
for (int i = 0; i < N; i++)
{
int flow_capacity = graph[s][i] - Flow[s][i];
if (!visited[i] && flow_capacity > 0)
// find min capacity in dfs path
if (int sent = dfs (i, t, min (minimum, flow_capacity)))
{
// adjust the capacity
Flow[s][i] += sent;
Flow[i][s] -= sent;
return sent;
}
}
return false;
}
int main()
{
// initialize initial flow capacity 0
memset(Flow, 0, sizeof(Flow));
// initialize visited array false initially
memset(visited, 0, sizeof(visited));
int s = 5;
int t = 6;
int max_flow = 0;
// while ther is augmenting path , from s and t
// with positive flow capacity
while (int sent = dfs(s, t, INF))
{
max_flow += sent;
// reset visited array , for searching next path
memset(visited, 0, sizeof(visited));
}
cout << "The max flow from node 5 to sink node 6 is " << max_flow;
cout << endl;
}
|
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow_using_bfs.cpp | #include <iostream>
// Part of Cosmos by OpenGenus Foundation //
#include <limits.h>
#include <string.h>
#include <queue>
using namespace std;
#define V 6
/* Returns true if there is a path from source 's' to sink 't' in
* residual graph. Also fills parent[] to store the path */
bool bfs(int rGraph[V][V], int s, int t, int parent[])
{
// Create a visited array and mark all vertices as not visited
bool visited[V];
memset(visited, 0, sizeof(visited));
// Create a queue, enqueue source vertex and mark source vertex
// as visited
queue <int> q;
q.push(s);
visited[s] = true;
parent[s] = -1;
// Standard BFS Loop
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v = 0; v < V; v++)
if (visited[v] == false && rGraph[u][v] > 0)
{
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
// If we reached sink in BFS starting from source, then return
// true, else false
return visited[t] == true;
}
// Returns tne maximum flow from s to t in the given graph
int fordFulkerson(int graph[V][V], int s, int t)
{
int u, v;
// Create a residual graph and fill the residual graph with
// given capacities in the original graph as residual capacities
// in residual graph
int rGraph[V][V]; // Residual graph where rGraph[i][j] indicates
// residual capacity of edge from i to j (if there
// is an edge. If rGraph[i][j] is 0, then there is not)
for (u = 0; u < V; u++)
for (v = 0; v < V; v++)
rGraph[u][v] = graph[u][v];
int parent[V]; // This array is filled by BFS and to store path
int max_flow = 0; // There is no flow initially
// Augment the flow while tere is path from source to sink
while (bfs(rGraph, s, t, parent))
{
// Find minimum residual capacity of the edges along the
// path filled by BFS. Or we can say find the maximum flow
// through the path found.
int path_flow = INT_MAX;
for (v = t; v != s; v = parent[v])
{
u = parent[v];
path_flow = min(path_flow, rGraph[u][v]);
}
// update residual capacities of the edges and reverse edges
// along the path
for (v = t; v != s; v = parent[v])
{
u = parent[v];
rGraph[u][v] -= path_flow;
rGraph[v][u] += path_flow;
}
// Add path flow to overall flow
max_flow += path_flow;
}
// Return the overall flow
return max_flow;
}
|
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow_using_bfs.java | // Part of Cosmos by OpenGenus Foundation
import java.util.LinkedList;
import java.lang.Exception;
class FordFulkersonUsingBfs {
static final int V = 6;
boolean bfs(int rGraph[][], int s, int t, int parent[]) {
/*
* Create a visited array and mark all vertices as not
* visited
*/
boolean visited[] = new boolean[V];
for(int i=0; i<V; ++i)
visited[i]=false;
/*
* Create a queue, enqueue source vertex and mark
* source vertex as visited
*/
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(s);
visited[s] = true;
parent[s]=-1;
// Standard BFS Loop
while (queue.size()!=0)
{
int u = queue.poll();
for (int v=0; v<V; v++)
{
if (visited[v]==false && rGraph[u][v] > 0)
{
queue.add(v);
parent[v] = u;
visited[v] = true;
}
}
}
/*
* If we reached sink in BFS starting from source, then
* return true, else false
*/
return (visited[t] == true);
}
// Returns tne maximum flow from s to t in the given graph
int fordFulkerson(int graph[][], int s, int t)
{
int u, v;
/*
* Create a residual graph and fill the residual graph
* with given capacities in the original graph as
* residual capacities in residual graph
*/
/*
* Residual graph where rGraph[i][j] indicates
* residual capacity of edge from i to j (if there
* is an edge. If rGraph[i][j] is 0, then there is
* not)
*/
int rGraph[][] = new int[V][V];
for (u = 0; u < V; u++)
for (v = 0; v < V; v++)
rGraph[u][v] = graph[u][v];
// This array is filled by BFS and to store path
int parent[] = new int[V];
int max_flow = 0; // There is no flow initially
/*
* Augment the flow while tere is path from source
* to sink
*/
while (bfs(rGraph, s, t, parent))
{
/*
*Find minimum residual capacity of the edhes
* along the path filled by BFS. Or we can say
* find the maximum flow through the path found.
*/
int pathFlow = Integer.MAX_VALUE;
for (v=t; v!=s; v=parent[v])
{
u = parent[v];
pathFlow = Math.min(pathFlow, rGraph[u][v]);
}
/*
* update residual capacities of the edges and
* reverse edges along the path
*/
for (v=t; v != s; v=parent[v])
{
u = parent[v];
rGraph[u][v] -= pathFlow;
rGraph[v][u] += pathFlow;
}
// Add path flow to overall flow
max_flow += pathFlow;
}
// Return the overall flow
return max_flow;
}
// Driver program to test above functions
public static void main (String[] args) throws java.lang.Exception {
// Example graph in adjancancy matrix
int graph[][] =new int[][] { {0, 16, 13, 0, 0, 0},
{0, 0, 10, 12, 0, 0},
{0, 4, 0, 0, 14, 0},
{0, 0, 9, 0, 0, 20},
{0, 0, 0, 7, 0, 4},
{0, 0, 0, 0, 0, 0}
};
FordFulkersonUsingBfs m = new FordFulkersonUsingBfs();
System.out.println("The maximum possible flow is " +
m.fordFulkerson(graph, 0, 5));
}
} |
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow_using_bfs.py | """
Part of Cosmos by OpenGenus Foundation
"""
from collections import defaultdict
# This class represents a directed graph using adjacency matrix representation
class Graph:
def __init__(self, graph):
self.graph = graph # residual graph
self.ROW = len(graph)
# self.COL = len(gr[0])
"""Returns true if there is a path from source 's' to sink 't' in
residual graph. Also fills parent[] to store the path """
def BFS(self, s, t, parent):
# Mark all the vertices as not visited
visited = [False] * (self.ROW)
# Create a queue for BFS
queue = []
# Mark the source node as visited and enqueue it
queue.append(s)
visited[s] = True
# Standard BFS Loop
while queue:
# Dequeue a vertex from queue and print it
u = queue.pop(0)
# Get all adjacent vertices of the dequeued vertex u
# If a adjacent has not been visited, then mark it
# visited and enqueue it
for ind, val in enumerate(self.graph[u]):
if visited[ind] == False and val > 0:
queue.append(ind)
visited[ind] = True
parent[ind] = u
# If we reached sink in BFS starting from source, then return
# true, else false
return True if visited[t] else False
# Returns tne maximum flow from s to t in the given graph
def FordFulkerson(self, source, sink):
# This array is filled by BFS and to store path
parent = [-1] * (self.ROW)
max_flow = 0 # There is no flow initially
# Augment the flow while there is path from source to sink
while self.BFS(source, sink, parent):
# Find minimum residual capacity of the edges along the
# path filled by BFS. Or we can say find the maximum flow
# through the path found.
path_flow = float("Inf")
s = sink
while s != source:
path_flow = min(path_flow, self.graph[parent[s]][s])
s = parent[s]
# Add path flow to overall flow
max_flow += path_flow
# update residual capacities of the edges and reverse edges
# along the path
v = sink
while v != source:
u = parent[v]
self.graph[u][v] -= path_flow
self.graph[v][u] += path_flow
v = parent[v]
return max_flow
# Create a graph given in the above diagram
print("Enter the number of vertices: ", end="")
m = int(input())
matrix = []
for i in range(0, m):
matrix.append([])
for j in range(0, m):
print("Enter the edge value from " + str(i) + " to " + str(j) + ": ", end="")
temp = int(input())
matrix[i].append(temp)
print("\nthe matrix is,\n")
for i in range(0, m):
for j in range(0, m):
print(matrix[i][j], " ", end="")
print("\n")
print("Enter the source: ", end="")
source = int(input())
print("Enter the sink: ", end="")
sink = int(input())
print("The maximum possible flow is %d " % g.FordFulkerson(source, sink))
|
code/graph_algorithms/src/graph_coloring/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/graph_coloring/graph_coloring.cpp | #include <iostream>
#include <list>
using namespace std;
// A class that represents an undirected graph
class Graph
{
int V; // No. of vertices
list<int> *adj; // A dynamic array of adjacency lists
public:
// Constructor and destructor
Graph(int V)
{
this->V = V; adj = new list<int>[V];
}
~Graph()
{
delete [] adj;
}
// function to add an edge to graph
void addEdge(int v, int w);
// Prints greedy coloring of the vertices
void greedyColoring();
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v); // Note: the graph is undirected
}
// Assigns colors (starting from 0) to all vertices and prints
// the assignment of colors
void Graph::greedyColoring()
{
int result[V];
// Assign the first color to first vertex
result[0] = 0;
// Initialize remaining V-1 vertices as unassigned
for (int u = 1; u < V; u++)
result[u] = -1; // no color is assigned to u
// A temporary array to store the available colors. True
// value of available[cr] would mean that the color cr is
// assigned to one of its adjacent vertices
bool available[V];
for (int cr = 0; cr < V; cr++)
available[cr] = false;
// Assign colors to remaining V-1 vertices
for (int u = 1; u < V; u++)
{
// Process all adjacent vertices and flag their colors
// as unavailable
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (result[*i] != -1)
available[result[*i]] = true;
// Find the first available color
int cr;
for (cr = 0; cr < V; cr++)
if (available[cr] == false)
break;
result[u] = cr; // Assign the found color
// Reset the values back to false for the next iteration
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (result[*i] != -1)
available[result[*i]] = false;
}
// print the result
for (int u = 0; u < V; u++)
cout << "Vertex " << u << " ---> Color "
<< result[u] << endl;
}
int main()
{
Graph g1(5);
g1.addEdge(0, 1);
g1.addEdge(0, 2);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 4);
cout << "Coloring of graph 1 \n";
g1.greedyColoring();
Graph g2(5);
g2.addEdge(0, 1);
g2.addEdge(0, 2);
g2.addEdge(1, 2);
g2.addEdge(1, 4);
g2.addEdge(2, 4);
g2.addEdge(4, 3);
cout << "\nColoring of graph 2 \n";
g2.greedyColoring();
return 0;
}
|
code/graph_algorithms/src/graph_coloring/graph_coloring.java | import java.util.*;
public class Coloring {
int minColors;
int[] bestColoring;
public int minColors(boolean[][] graph) {
int n = graph.length;
bestColoring = new int[n];
int[] id = new int[n + 1];
int[] deg = new int[n + 1];
for (int i = 0; i <= n; i++)
id[i] = i;
bestColoring = new int[n];
int res = 1;
for (int from = 0, to = 1; to <= n; to++) {
int best = to;
for (int i = to; i < n; i++) {
if (graph[id[to - 1]][id[i]])
++deg[id[i]];
if (deg[id[best]] < deg[id[i]])
best = i;
}
int t = id[to];
id[to] = id[best];
id[best] = t;
if (deg[id[to]] == 0) {
minColors = n + 1;
dfs(graph, id, new int[n], from, to, from, 0);
from = to;
res = Math.max(res, minColors);
}
}
return res;
}
void dfs(boolean[][] graph, int[] id, int[] coloring, int from, int to, int cur, int usedColors) {
if (usedColors >= minColors)
return;
if (cur == to) {
for (int i = from; i < to; i++)
bestColoring[id[i]] = coloring[i];
minColors = usedColors;
return;
}
boolean[] used = new boolean[usedColors + 1];
for (int i = 0; i < cur; i++)
if (graph[id[cur]][id[i]])
used[coloring[i]] = true;
for (int i = 0; i <= usedColors; i++) {
if (!used[i]) {
int tmp = coloring[cur];
coloring[cur] = i;
dfs(graph, id, coloring, from, to, cur + 1, Math.max(usedColors, i + 1));
coloring[cur] = tmp;
}
}
}
public static void main(String[] args) {
Random rnd = new Random(1);
for (int step = 0; step < 1000; step++) {
int n = rnd.nextInt(10) + 1;
boolean[][] g = new boolean[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
if (rnd.nextBoolean()) {
g[i][j] = true;
g[j][i] = true;
}
int res1 = new Coloring().minColors(g);
int res2 = colorSlow(g);
if (res1 != res2)
throw new RuntimeException();
}
}
static int colorSlow(boolean[][] g) {
int n = g.length;
for (int allowedColors = 1; ; allowedColors++) {
long colors = 1;
for (int i = 0; i < n; i++)
colors *= allowedColors;
m1:
for (long c = 0; c < colors; c++) {
int[] col = new int[n];
long cur = c;
for (int i = 0; i < n; i++) {
col[i] = (int) (cur % allowedColors);
cur /= allowedColors;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
if (g[i][j] && col[i] == col[j])
continue m1;
return allowedColors;
}
}
}
}
|
code/graph_algorithms/src/graph_coloring/graph_coloring_greedy.py | from collections import defaultdict
class Graph:
def __init__(self, V, directed=False):
self.V = V
self.directed = directed
self.graph = defaultdict(list)
def add_edge(self, a, b):
self.graph[a].append(b)
if not self.directed:
self.graph[b].append(a)
def color_greedy(self):
result = [-1] * self.V
max_color = 0
for v, adj in self.graph.items():
color = 0
while color in [result[x] for x in adj]:
color += 1
max_color = max(max_color, color)
result[v] = color
return result, max_color
if __name__ == "__main__":
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 3)
g.add_edge(3, 4)
res, m = g.color_greedy()
print("max colors: {} list: {}".format(m, res))
|
code/graph_algorithms/src/hamiltonian_cycle/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/hamiltonian_cycle/hamiltonian_cycle.java | import java.util.Scanner;
class HamiltonCycle {
final static int MAX = 10;
static int NO_VER = MAX;
int path[];
public static void main(String args[]) {
HamiltonCycle hamiltonian = new HamiltonCycle();
Scanner in = new Scanner(System.in);
System.out.println("Backtracking Hamiltonian Cycle Algorithm:\n");
// Accept number of vertices
System.out.print("Enter number of vertices:\t");
NO_VER = in.nextInt();
// Get graph
System.out.println("\nEnter the adjacency matrix:\n");
int[][] graph = new int[NO_VER][NO_VER];
for (int i = 0; i < NO_VER; i++)
for (int j = 0; j < NO_VER; j++)
graph[i][j] = in.nextInt();
// Print the solution
hamiltonian.hamCycle(graph);
}
boolean isSafe(int v, int graph[][], int path[], int pos) {
// Check if this vertex is an adjacent vertex
if (graph[path[pos - 1]][v] == 0)
return false;
// Check if the vertex has already been included.
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
boolean findHamCycle(int graph[][], int path[], int pos) {
// Check if all vertices have been included
if (pos == NO_VER) {
// Check if there is an edge from the last vertex to the source vertex
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
// Try different vertices as a next vertex
for (int v = 1; v < NO_VER; v++) {
// Check if this vertex can be added to Hamiltonian Cycle
if (isSafe(v, graph, path, pos)) {
path[pos] = v;
// Construct rest of the path
if (findHamCycle(graph, path, pos + 1) == true)
return true;
// If adding vertex v doesn't lead to a solution, then remove it
path[pos] = -1;
}
}
// If no vertex can be added, then return false
return false;
}
int hamCycle(int graph[][]) {
path = new int[NO_VER];
//Initialize
for (int i = 0; i < NO_VER; i++)
path[i] = -1;
//Set source
path[0] = 0;
if (findHamCycle(graph, path, 1) == false) {
System.out.println("\nSolution does not exist!");
return 0;
}
printSolution(path);
return 1;
}
void printSolution(int path[]) {
System.out.println("Solution Exists! \nFollowing is one of Hamiltonian Cycle:\n");
for (int i = 0; i < NO_VER; i++)
System.out.print(" " + path[i] + " --> ");
// Print the first vertex again to show the complete cycle
System.out.println(path[0] + " ");
}
}
|
code/graph_algorithms/src/hamiltonian_cycle/hamiltonian_cycle.py | # Part of Cosmos by OpenGenus Foundation
# Python program for solution of
# hamiltonian cycle problem
class Graph:
def __init__(self, vertices):
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
self.V = vertices
""" Check if this vertex is an adjacent vertex
of the previously added vertex and is not
included in the path earlier """
def isSafe(self, v, pos, path):
# Check if current vertex and last vertex
# in path are adjacent
if self.graph[path[pos - 1]][v] == 0:
return False
# Check if current vertex not already in path
for vertex in path:
if vertex == v:
return False
return True
# A recursive utility function to solve
# hamiltonian cycle problem
def hamCycleUtil(self, path, pos):
# base case: if all vertices are
# included in the path
if pos == self.V:
# Last vertex must be adjacent to the
# first vertex in path to make a cyle
if self.graph[path[pos - 1]][path[0]] == 1:
return True
else:
return False
# Try different vertices as a next candidate
# in Hamiltonian Cycle. We don't try for 0 as
# we included 0 as starting point in in hamCycle()
for v in range(1, self.V):
if self.isSafe(v, pos, path) == True:
path[pos] = v
if self.hamCycleUtil(path, pos + 1) == True:
return True
# Remove current vertex if it doesn't
# lead to a solution
path[pos] = -1
return False
def hamCycle(self):
path = [-1] * self.V
""" Let us put vertex 0 as the first vertex
in the path. If there is a Hamiltonian Cycle,
then the path can be started from any point
of the cycle as the graph is undirected """
path[0] = 0
if self.hamCycleUtil(path, 1) == False:
print("Solution does not exist\n")
return False
self.printSolution(path)
return True
def printSolution(self, path):
print("Solution Exists: Following is one Hamiltonian Cycle")
for vertex in path:
print(vertex, end="")
print(path[0])
# Driver Code
""" Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) """
g1 = Graph(5)
g1.graph = [
[0, 1, 0, 1, 0],
[1, 0, 1, 1, 1],
[0, 1, 0, 0, 1],
[1, 1, 0, 0, 1],
[0, 1, 1, 1, 0],
]
# Print the solution
g1.hamCycle()
""" Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) """
g2 = Graph(5)
g2.graph = [
[0, 1, 0, 1, 0],
[1, 0, 1, 1, 1],
[0, 1, 0, 0, 1],
[1, 1, 0, 0, 0],
[0, 1, 1, 0, 0],
]
# Print the solution
g2.hamCycle()
|
code/graph_algorithms/src/hamiltonian_path/hamiltonian_path.cpp | #include <iostream>
#include <vector>
#include <bitset>
#include <cmath>
#include <cstdlib>
#include <cstring>
using namespace std;
const int MAXN = 8000;
const int INF = (int)1e9;
int n, m, *deg, *par, tl = -1;
bool *used;
vector <vector <int>> G;
inline void count_degs()
{
for (int i = 0; i < n; i++)
deg[i] = G[i].size();
}
bool DFS(int v, int p = -1)
{
tl = v;
used[v] = 1;
par[v] = p;
int gmin = INF;
int cnt = 1;
for (unsigned int i = 0; i < G[v].size(); i++)
deg[G[v][i]]--;
for (unsigned int i = 0; i < G[v].size(); i++)
if (!used[G[v][i]])
{
if (deg[G[v][i]] < gmin)
{
gmin = deg[G[v][i]];
cnt = 1;
}
else if (deg[G[v][i]] == gmin)
cnt++;
}
int num = rand() % cnt;
cnt = 0;
for (unsigned int i = 0; i < G[v].size(); i++)
if (!used[G[v][i]])
if (deg[G[v][i]] == gmin)
if (cnt++ == num)
return DFS(G[v][i], v);
return false;
}
int main()
{
cin >> n >> m;
deg = new int[n];
par = new int[n];
used = new bool[n];
G.resize(n);
for (int i = 0; i < m; i++)
{
int t1, t2;
cin >> t1 >> t2;
G[--t1].push_back(--t2);
G[t2].push_back(t1);
}
for (int iter = 0;; iter++)
{
tl = -1;
count_degs();
memset(used, 0, n * sizeof(used[0]));
memset(par, 0, n * sizeof(par[0]));
int vert = rand() % n;
DFS(vert);
bool flag = true;
for (int j = 0; j < n; j++)
if (!used[j])
flag = false;
if (flag)
{
for (int j = tl; j != -1; j = par[j])
cout << j + 1;
cout << "\n";
return 0;
}
}
}
|
code/graph_algorithms/src/hopcroft_karp_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/johnson_algorithm_shortest_path/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/johnson_algorithm_shortest_path/johnson_algorithm_shortest_path.py | # Part of Cosmos by OpenGenus Foundation
"""
def Johnsons():
data = list()
source = list()
destination = list()
edgecost = list()
test = 0
vertices = 0
edges = 0
data = readfile()
vertexlist = list()
distance = list()
vertices, edges, source, destination, edgecost, vertexlist, distance = setdata(data)
predecessor = list()
d = list()
d, predecessor = intialize(distance)
#relaxation
source, destination, edgecost, d, predecessor = relax(vertices, source, destination, edgecost, d, predecessor,edges)
#change weights
vertexlist.reverse()
source, destination, edgecost, d = reweight(vertices, source, destination, edgecost, d,edges)
output(source, destination, edgecost)
for x in vertexlist:
print('Running Dijkstra on vertex ' + str(x))
Dijkstra(vertexlist,x,source, destination, edgecost, predecessor, edges,vertices)
"""
from heapq import heappush, heappop
from datetime import datetime
from copy import deepcopy
graph = {
"a": {"b": -2},
"b": {"c": -1},
"c": {"x": 2, "a": 4, "y": -3},
"z": {"x": 1, "y": -4},
"x": {},
"y": {},
}
inf = float("inf")
dist = {}
def read_graph(file, n):
graph = dict()
with open(file) as f:
for l in f:
(u, v, w) = l.split()
if int(u) not in graph:
graph[int(u)] = dict()
graph[int(u)][int(v)] = int(w)
for i in range(n):
if i not in graph:
graph[i] = dict()
return graph
def dijkstra(graph, s):
n = len(graph.keys())
dist = dict()
Q = list()
for v in graph:
dist[v] = inf
dist[s] = 0
heappush(Q, (dist[s], s))
while Q:
d, u = heappop(Q)
if d < dist[u]:
dist[u] = d
for v in graph[u]:
if dist[v] > dist[u] + graph[u][v]:
dist[v] = dist[u] + graph[u][v]
heappush(Q, (dist[v], v))
return dist
def initialize_single_source(graph, s):
for v in graph:
dist[v] = inf
dist[s] = 0
def relax(graph, u, v):
if dist[v] > dist[u] + graph[u][v]:
dist[v] = dist[u] + graph[u][v]
def bellman_ford(graph, s):
initialize_single_source(graph, s)
edges = [(u, v) for u in graph for v in graph[u].keys()]
number_vertices = len(graph)
for i in range(number_vertices - 1):
for (u, v) in edges:
relax(graph, u, v)
for (u, v) in edges:
if dist[v] > dist[u] + graph[u][v]:
return False # there exists a negative cycle
return True
def add_extra_node(graph):
graph[0] = dict()
for v in graph.keys():
if v != 0:
graph[0][v] = 0
def reweighting(graph_new):
add_extra_node(graph_new)
if not bellman_ford(graph_new, 0):
# graph contains negative cycles
return False
for u in graph_new:
for v in graph_new[u]:
if u != 0:
graph_new[u][v] += dist[u] - dist[v]
del graph_new[0]
return graph_new
def johnsons(graph_new):
graph = reweighting(graph_new)
if not graph:
return False
final_distances = {}
for u in graph:
final_distances[u] = dijkstra(graph, u)
for u in final_distances:
for v in final_distances[u]:
final_distances[u][v] += dist[v] - dist[u]
return final_distances
def compute_min(final_distances):
return min(
final_distances[u][v] for u in final_distances for v in final_distances[u]
)
if __name__ == "__main__":
# graph = read_graph("graph.txt", 1000)
graph_new = deepcopy(graph)
t1 = datetime.utcnow()
final_distances = johnsons(graph_new)
if not final_distances:
print("Negative cycle")
else:
print(compute_min(final_distances))
print(datetime.utcnow() - t1)
|
code/graph_algorithms/src/karger_minimum_cut/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/karger_minimum_cut/karger_minimum_cut.java | /*
Sample Input
8
1 2 4 3
2 1 3 4 5
3 1 2 4
4 3 1 2 7
5 2 6 8 7
6 5 7 8
7 4 5 6 8
8 7 6 5
Here, first number is the node number and the following numbers in each row are it's adjacent rows.
Sample Output
Minimum Cut=2
*/
import java.lang.*;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class karger
{
public static int [][] merge(int a[][],int rn1,int rn2)
{
int i,len;
int k=0;
for(i=a[rn1-1][0]+2;i<a[rn1-1][0]+2+a[rn2-1][0];i++)
{
a[rn1-1][i]=a[rn2-1][i-a[rn1-1][0]];
a[rn2-1][i-a[rn1-1][0]]=0;
}
a[rn1-1][0]+=a[rn2-1][0];
a[rn2-1][0]=0;
for(i=2;i<a[rn1-1][0]+2;i++)
if(a[rn1-1][i]==rn1 || a[rn1-1][i]==rn2)
a[rn1-1][i]=0;
len=a[rn1-1][0];
int temp[]=new int[len];
for(i=2;i<a[rn1-1][0]+2;i++)
if(a[rn1-1][i]!=0)
temp[k++]=a[rn1-1][i];
a[rn1-1][0]=k;
for(i=2;i<len+2;i++)
a[rn1-1][i]=temp[i-2];
return a;
}
public static int no_of_rows(int arr[][])
{
int i,l=0;
for(i=0;i<arr.length;i++)
if(arr[i][0]!=0)
l++;
return l;
}
public static void main(String args[])
{
String str="";
int i,j,z,rn1,rn2,col_len;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of nodes=");
int nodes=sc.nextInt();
str=sc.nextLine();
int min_cut=nodes;
int a[][]=new int[nodes][nodes*nodes];
for(i=0;i<nodes;i++)
{
str=sc.nextLine();
str=str+" ";
while(str.length()>0)
{
str.trim();
a[i][++a[i][0]]=Integer.parseInt(str.substring(0,str.indexOf(' ')));
str=str.substring(str.indexOf(' ')+1);
}
}
System.out.println();
for(i=0;i<nodes;i++)
a[i][0]-=1;
int [][] backup_a = new int[a.length][];
for(int y = 0; y < a.length; y++)
backup_a[y] = a[y].clone();
for(z=1;z<=nodes*nodes*nodes;z++)
{
for(int y = 0; y < backup_a.length; y++)
a[y] = backup_a[y].clone();
col_len=no_of_rows(a);
while(col_len>2)
{
rn1=ThreadLocalRandom.current().nextInt(1,nodes+1);
rn2=ThreadLocalRandom.current().nextInt(1,nodes+1);
while(a[rn1-1][0]==0)
rn1=ThreadLocalRandom.current().nextInt(1,nodes+1);
while(a[rn2-1][0]==0 || rn1==rn2)
rn2=a[rn1-1][ThreadLocalRandom.current().nextInt(2,a[rn1-1][0]+2)];
for(i=0;i<nodes;i++)
{
if(i==(rn1-1) || i==(rn2-1))
continue;
for(j=2;j<(2+a[i][0]);j++)
if(a[i][j]==rn2)
a[i][j]=rn1;
}
a=merge(a,rn1,rn2);
col_len=no_of_rows(a);
}
i=0;
while(true)
{
if(a[i][0]!=0)
{
if(a[i][0]<min_cut)
min_cut=a[i][0];
break;
}
i++;
}
}
System.out.println("Minimum Cut="+min_cut);
}
} |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.c | // Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
#include<stdlib.h>
#define VAL 999
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
// union - find
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
int main()
{
printf("Implementation of Kruskal's algorithm\n");
printf("Enter the no. of vertices:");
scanf("%d",&n);
printf("Enter the cost adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=VAL;
}
}
printf("The edges of Minimum Cost Spanning Tree are\n");
while(ne < n)
{
for(i=1,min=VAL;i<=n;i++)
{
for(j=1;j <= n;j++)
{
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
// printing edges
printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
// minimum cost
printf("\n\tMinimum cost = %d\n",mincost);
return 0;
}
|
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.cpp | #include <iostream>
#include <vector>
#include <algorithm>
// Part of Cosmos by OpenGenus Foundation
int n, dj[100], rank[100]; //disjoint set
int findset(int a)
{
if (dj[a] != a)
return dj[a] = findset(dj[a]);
else
return a;
}
bool sameset(int a, int b)
{
return findset(a) == findset(b);
}
void unionset(int a, int b)
{
int x = findset(a), y = findset(b);
if (rank[x] > rank[y])
dj[y] = x;
else
{
dj[x] = y;
if (rank[x] == rank[y])
rank[y]++;
}
}
int main()
{
using namespace std;
int e, u, v, w;
vector< pair<int, pair<int, int>>> edge; //(weight, two vertices that the edge connects)
for (int i = 0; i < n; i++)
{
dj[i] = i;
::rank[i] = 0;
}
cout << "Input Number of Edges" << endl;
cin >> e;
cout << "Input Edges (weight and then two vertices that the edge connects)" << endl;
for (int i = 0; i < e; i++)
{
cin >> u >> v >> w; //u,v,w are just temporary variables
edge.push_back({u, {v, w}});
}
sort(edge.begin(), edge.end()); //sort by edge weight
int mst = 0;
for (int i = 0; i < e; i++)
{
int x = edge[i].second.first, y = edge[i].second.second;
if (!sameset(x, y))
{
mst += edge[i].first;
unionset(x, y);
}
}
cout << mst << endl;
}
|
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.java | /* Java program for Kruskal's algorithm to find Minimum
* Spanning Tree of a given connected, undirected and
* weighted graph
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class Graph
{
// A class to represent a graph edge
class Edge implements Comparable<Edge>
{
int src, dest, weight;
/* Comparator function used for sorting edges
* based on their weight
*/
public int compareTo(Edge compareEdge)
{
return this.weight-compareEdge.weight;
}
};
// A class to represent a subset for union-find
class subset
{
int parent, rank;
};
int V, E; // V-> no. of vertices & E->no.of edges
Edge edge[]; // collection of all edges
// Creates a graph with V vertices and E edges
Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[E];
for (int i=0; i<e; ++i)
edge[i] = new Edge();
}
// A utility function to find set of an element i
// (uses path compression technique)
int find(subset subsets[], int i)
{
// find root and make root as parent of i (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// Attach smaller rank tree under root of high rank tree
// (Union by Rank)
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
// If ranks are same, then make one as root and increment
// its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// The main function to construct MST using Kruskal's algorithm
void KruskalMST()
{
Edge result[] = new Edge[V]; // Tnis will store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges
for (i=0; i<V; ++i)
result[i] = new Edge();
// Step 1: Sort all the edges in non-decreasing order of their
// weight. If we are not allowed to change the given graph, we
// can create a copy of array of edges
Arrays.sort(edge);
// Allocate memory for creating V ssubsets
subset subsets[] = new subset[V];
for(i=0; i<V; ++i)
subsets[i]=new subset();
// Create V subsets with single elements
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
i = 0; // Index used to pick next edge
// Number of edges to be taken is equal to V-1
while (e < V - 1)
{
// Step 2: Pick the smallest edge. And increment
// the index for next iteration
Edge next_edge = new Edge();
next_edge = edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
// If including this edge does't cause cycle,
// include it in result and increment the index
// of result for next edge
if (x != y)
{
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}
// print the contents of result[] to display
// the built MST
System.out.println("Following are the edges in " +
"the constructed MST");
for (i = 0; i < e; ++i)
System.out.println(result[i].src+" -- " +
result[i].dest+" == " + result[i].weight);
}
// Driver Program
public static void main (String[] args)
{
/*
10
0--------1
| \ |
6| 5\ |15
| \ |
2--------3
4 */
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
Graph graph = new Graph(V, E);
// add edge 0-1
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = 10;
// add edge 0-2
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 6;
// add edge 0-3
graph.edge[2].src = 0;
graph.edge[2].dest = 3;
graph.edge[2].weight = 5;
// add edge 1-3
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 15;
// add edge 2-3
graph.edge[4].src = 2;
graph.edge[4].dest = 3;
graph.edge[4].weight = 4;
graph.KruskalMST();
}
} |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.py | from collections import defaultdict
# Part of Cosmos by OpenGenus Foundation
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def KruskalMST(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
print("Constructed MST :")
print("Vertex A Vertex B Weight")
for u, v, weight in result:
print(" %d %d %d" % (u, v, weight))
# vetx = int(input("Enter no. of vertices :"))
eegde = int(input("Enter no. of edges :"))
g = Graph(eegde - 1)
print(
"For each edge input (Source vertex , Destination vertex , Weight of the edge ) :"
)
for x in range(eegde):
qq, xx, yy = map(int, input().split(" "))
g.addEdge(qq, xx, yy)
g.KruskalMST()
|
code/graph_algorithms/src/kuhn_maximum_matching/kuhn_maximum_matching.cpp | /*
* BY:- https://github.com/alphaWizard
*
* algorithm:- finds maximum bipartite matching for a given bipartite graph
* by taking input number of nodes(n) and number of edges(m)
*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
std::vector<int> adj[10000];
bool mark[10000];
int match[10000];
void init()
{
for (int i = 0; i < 10000; ++i)
{
match[i] = -1; adj[i].clear();
}
}
bool dfs(int u)
{
for (int i = adj[u].size() - 1; i >= 0; --i)
{
int v = adj[u][i];
if (!mark[v])
{
mark[v] = true;
if (match[v] == -1 || dfs(match[v]))
{
match[v] = u;
return true;
}
}
}
return false;
}
int main()
{
using namespace std;
init();
int n, m;
cin >> n >> m;
for (int i = 0; i < m; ++i)
{
int a, b; cin >> a >> b;
adj[a].push_back(b);
}
int ct = 0;
for (int i = 1; i <= n; ++i)
{
for (int j = 0; j < 10000; ++j)
mark[j] = false;
if (dfs(i))
++ct;
}
cout << ct << endl;
return 0;
}
|
code/graph_algorithms/src/kuhn_munkres_algorithm/kuhn_munkres_algorithm.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* Kuhn-Munkres algorithm: find the perfect matching in a balanced and weighted bipartite graph
* that gives the maximum sum of weights.
*/
#include <memory>
#include <vector>
#include <type_traits>
#include <limits>
#include <algorithm>
#include <iostream>
#include <initializer_list>
template
<
typename _WeightType,
typename = std::enable_if<
std::is_integral<_WeightType>::value && std::is_signed<_WeightType>::value>::type
>
class KuhnMunkresAlgorithm
{
public:
/*
* InputVector[i][j] contains the weight of the edge between Left node i and right node j.
* Let UpperLimit = std::numeric_limits<_WeightType>::max()/3 and LowerLimit = -UpperLimit,
* please make sure weights of edges are within range (LowerLimit, UpperLimit).
* If there is no edge between Left node i and right node j, set the weight to LowerLimit.
* At least one perfect matching must exist in the input bipartite graph.
*/
using InputType = std::vector<std::vector<_WeightType>>;
public:
explicit KuhnMunkresAlgorithm(const std::shared_ptr<InputType> Input) noexcept
: LeftsCount_(Input->size()),
RightsCount_((*Input)[0].size()),
leftsVisited_(LeftsCount_),
rightsVisited_(RightsCount_),
leftsLabel_(LeftsCount_),
rightsLabel_(RightsCount_),
Input_{Input}
{
}
/*
* Returns the perfect matching that gives the maximum sum of weights, represented by a vector.
* The index of the vector is the index of a right node. The element stored in the vector is the
* index of the Left node that is matched with the right node.
*/
std::vector<ptrdiff_t> run() noexcept
{
// Initialize the matching. At the beginning, no match exists in the matching.
std::vector<ptrdiff_t> matching(RightsCount_,
-1 /* -1 means this right node is unmatched. */);
// Initialize labels of Left nodes (labels of right nodes are already initialized to 0).
for (ptrdiff_t Left = 0; Left < LeftsCount_; ++Left)
{
_WeightType maxWeight = LowerLimit_;
for (ptrdiff_t right = 0; right < RightsCount_; ++right)
maxWeight = std::max(maxWeight, (*Input_)[Left][right]);
leftsLabel_[Left] = maxWeight;
}
for (ptrdiff_t Left = 0; Left < LeftsCount_; ++Left)
{
leftsVisited_.assign(LeftsCount_, false);
rightsVisited_.assign(RightsCount_, false);
diff_ = UpperLimit_;
while (!dfs(Left, matching)) // This loop won't exit until an augmenting path is found.
{
// Update labels.
for (ptrdiff_t i = 0; i < LeftsCount_; ++i)
if (leftsVisited_[i])
leftsLabel_[i] -= diff_;
for (ptrdiff_t j = 0; j < RightsCount_; ++j)
if (rightsVisited_[j])
rightsLabel_[j] += diff_;
leftsVisited_.assign(LeftsCount_, false);
rightsVisited_.assign(RightsCount_, false);
diff_ = UpperLimit_;
}
}
return matching;
}
private:
bool dfs(const ptrdiff_t Left, std::vector<ptrdiff_t> &matching) noexcept
{
leftsVisited_[Left] = true;
// Try to find an augmenting path.
for (ptrdiff_t right = 0; right < RightsCount_; ++right)
{
if (rightsVisited_[right])
continue; // Only an unvisited right node counts.
_WeightType t = leftsLabel_[Left] + rightsLabel_[right] - (*Input_)[Left][right];
if (t == 0) // In an equal subgraph.
{
rightsVisited_[right] = true;
if (matching[right] == -1 || dfs(matching[right], matching))
{
// Augmenting path found, update the matching.
matching[right] = Left;
return true;
}
}
else
diff_ = std::min(diff_, t);
}
return false;
}
private:
const ptrdiff_t LeftsCount_;
const ptrdiff_t RightsCount_;
_WeightType diff_ = UpperLimit_;
std::vector<bool> leftsVisited_;
std::vector<bool> rightsVisited_;
std::vector<_WeightType> leftsLabel_;
std::vector<_WeightType> rightsLabel_;
const std::shared_ptr<const InputType> Input_;
public:
static constexpr _WeightType UpperLimit_ = std::numeric_limits<_WeightType>::max() / 3;
static constexpr _WeightType LowerLimit_ = -UpperLimit_;
};
int main()
{
const int non = KuhnMunkresAlgorithm<int>::LowerLimit_;
const auto input = std::make_shared<KuhnMunkresAlgorithm<int>::InputType>(
std::initializer_list<std::vector<int>>{
{ 200, non, 180, 180, non, 190, non, 195 },
{ non, non, non, 170, 185, 186, 187, non },
{ non, 189, 170, 166, 160, non, non, 191 },
{ 160, 167, non, non, 200, 198, 195, 202 },
{ non, 170, 184, non, 202, 198, 169, 205 },
{ non, non, 187, 204, non, 185, 200, non },
{ 170, 170, 170, 170, 170, 170, 170, 170 },
{ non, 170, 169, 174, non, non, non, 197 }
});
KuhnMunkresAlgorithm<int> algorithm{input};
std::vector<ptrdiff_t> result = algorithm.run();
for (ptrdiff_t i = 0; i < result.size(); ++i)
std::cout << "right node " << i << " is matched with left node " << result[i] << ".\n";
std::cin.get();
return 0;
}
|
code/graph_algorithms/src/left_view_binary_tree/left_view_binary_tree.cpp | #include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
struct node
{
int d;
node *left;
node *right;
};
struct node* newnode(int num)
{
node *temp = new node;
temp->d = num;
temp->left = temp->right = NULL;
return temp;
}
void lefttree(struct node *root, int level, int *maxlevel)
{
if (root == NULL)
return;
if (*maxlevel < level)
{
cout << root->d << endl;
*maxlevel = level;
}
lefttree(root->left, level + 1, maxlevel);
lefttree(root->right, level + 1, maxlevel);
}
int main()
{
node *root = newnode(12);
root->left = newnode(10);
root->right = newnode(30);
root->right->left = newnode(25);
root->right->right = newnode(40);
int maxlevel = 0;
lefttree(root, 1, &maxlevel);
cout << endl;
return 0;
}
|
code/graph_algorithms/src/left_view_binary_tree/left_view_binary_tree.java | // Part of Cosmos by OpenGenus Foundation
// This class prints the left nodes of a binary tree
class Node {
int data;
Node left;
Node right;
public Node(int node) {
data = node;
left = right = null;
}
}
class BinaryTree {
Node root; // Define root node
int max_level = 0; // Define max level
// Recursive function that prints left nodes of tree
void printLeftView(Node node, int cur_level) {
if (node == null) return;
if (max_level < cur_level) {
System.out.print(node.data + " ");
max_level = cur_level;
}
// Recurisely traverse along the left and right nodes of child node
printLeftView(node.left, cur_level + 1);
printLeftView(node.right, cur_level + 1);
}
void leftView() {
printLeftView(root, 1);
}
public static void main(String args[]) {
// Binary tree test
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
System.out.print("Left nodes of binary tree: ");
tree.leftView();
}
} |
code/graph_algorithms/src/left_view_binary_tree/left_view_binary_tree.py | # Part of Cosmos by OpenGenus Foundation
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Recursive function pritn left view of a binary tree
def leftViewUtil(root, level, max_level):
# Base Case
if root is None:
return
# If this is the first node of its level
if max_level[0] < level:
print("%d\n" % (root.data), end=" ")
max_level[0] = level
# Recur for left and right subtree
leftViewUtil(root.left, level + 1, max_level)
leftViewUtil(root.right, level + 1, max_level)
# A wrapper over leftViewUtil()
def leftView(root):
max_level = [0]
leftViewUtil(root, 1, max_level)
# Driver program to test above function
root = Node(12)
root.left = Node(10)
root.right = Node(20)
root.right.left = Node(25)
root.right.right = Node(40)
leftView(root)
|
code/graph_algorithms/src/longest_path_directed_acyclic_graph/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/longest_path_directed_acyclic_graph/longest_path_directed_acyclic_graph.cpp | #include <iostream>
#include <vector>
#include <algorithm>
/* Part of Cosmos by OpenGenus Foundation */
void dfs(int v, std::vector<std::vector<int>> &g, std::vector<int> &dp)
{
if (dp[v])
return;
dp[v] = 1;
for (int u : g[v])
{
dfs(u, g, dp);
dp[v] = std::max(dp[v], dp[u] + 1);
}
}
// Time complexity: O(|V| + |E|)
std::vector<int> longest_path_directed_acyclic_graph(std::vector<std::vector<int>> &g)
{
int n = (int) g.size();
std::vector<int> dp(n);
for (int i = 0; i < n; i++)
if (!dp[i])
dfs(i, g, dp);
int start = (int) (max_element(dp.begin(), dp.end()) - dp.begin());
int dist = dp[start] - 1;
std::vector<int> res;
res.push_back(start);
while (dist > 0)
{
for (int nxt : g[start])
if (dp[nxt] == dist)
{
start = nxt;
dist--;
res.push_back(start);
break;
}
}
return res;
}
int main()
{
std::cout << "Enter the number of vertexes:" << std::endl;
int n;
std::cin >> n;
std::cout << "Enter the number of edges:" << std::endl;
int m;
std::cin >> m;
std::cout <<
"Enter the edges in the following format: u v -- an edge from u to v. 0 <= u, v < n" <<
std::endl;
std::vector<std::vector<int>> g(n);
for (int i = 0; i < m; i++)
{
int u, v;
std::cin >> u >> v;
g[u].push_back(v);
}
std::cout << "Longest path:\n";
for (int v : longest_path_directed_acyclic_graph(g))
std::cout << v << " ";
std::cout << "\n";
return 0;
}
|
code/graph_algorithms/src/lowest_common_ancestor/lowest_common_ancestor.cpp | #include <iostream>
#include <vector>
#include <array>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// Problem Statement
/*
* Given a tree with n nodes
* Your task is to process q queries of the following form:
* who is the lowest common ancestor of nodes a and b in the tree?
*
* The lowest common ancestor of two nodes of a rooted tree is the lowest node
* whose subtree contains both the nodes.
*/
void dfs(int k, int p, vector<int> &depth, vector<vector<int>> &adj, vector<array<int, 20>> &ancestor)
{
ancestor[k][0] = p;
depth[k] = depth[p] + 1;
for (int i = 1; i < 20; i++)
ancestor[k][i] = ancestor[ancestor[k][i - 1]][i - 1];
for (int i : adj[k])
if (i != p)
dfs(i, k, depth, adj, ancestor);
}
int kthAncestor(int k, int x, vector<array<int, 20>> &ancestor)
{
for (int i = 0; i < 20; i++)
if (x & (1 << i))
k = ancestor[k][i];
return k;
}
int lca(int a, int b, vector<array<int, 20>> &ancestor, vector<int> &depth)
{
if (depth[a] < depth[b])
swap(a, b);
a = kthAncestor(a, depth[a] - depth[b], ancestor);
if (a == b)
return b;
for (int i = 19; i >= 0; i--)
if (ancestor[a][i] != ancestor[b][i])
a = ancestor[a][i], b = ancestor[b][i];
return ancestor[a][0];
}
int main()
{
int n;
cin >> n;
vector<vector<int>> adj(n + 1);
for (int i = 1; i < n; i++)
{
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<int> depth(n + 1);
vector<array<int, 20>> ancestor(n + 1);
dfs(1, 0, depth, adj, ancestor);
int q;
cin >> q;
while (q--)
{
int a, b;
cin >> a >> b;
cout << lca(a, b, ancestor, depth) << '\n';
}
}
|
code/graph_algorithms/src/matrix_transformation/matrix_transformation.swift | // Part of Cosmos by OpenGenus Foundation
import Foundation
class MatrixTransformation {
func rotate<T>(_ matrix: inout [[T]]) {
guard matrix.count > 0 && matrix.count == matrix[0].count else {
return
}
// 1 2 3 7 8 9 7 4 1
// 4 5 6 => 4 5 6 => 8 5 2
// 7 8 9 1 2 3 9 6 3
matrix.reverse()
squareTranspose(&matrix)
}
func reverseRotate<T>(_ matrix: inout [[T]]) {
guard matrix.count > 0 && matrix.count == matrix[0].count else {
return
}
// 1 2 3 3 2 1 3 6 9
// 4 5 6 => 6 5 4 => 2 5 8
// 7 8 9 9 8 7 1 4 7
for i in 0..<matrix.count {
matrix[i].reverse()
}
squareTranspose(&matrix)
}
func squareTranspose<T>(_ matrix: inout [[T]]) {
guard matrix.count > 0 && matrix.count == matrix[0].count else {
return
}
// 1 2 3 1 4 7
// 4 5 6 => 2 5 8
// 7 8 9 3 6 9
for i in 0..<matrix.count {
for j in i..<matrix.count {
(matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j])
}
}
}
func antiSquareTranspose<T>(_ matrix: inout [[T]]) {
guard matrix.count > 0 && matrix.count == matrix[0].count else {
return
}
// 1 2 3 9 6 3
// 4 5 6 => 8 5 2
// 7 8 9 7 4 1
for i in 0..<matrix.count {
for j in 0..<matrix.count - i {
(matrix[i][j], matrix[matrix.count - j - 1][matrix.count - i - 1])
= (matrix[matrix.count - j - 1][matrix.count - i - 1], matrix[i][j])
}
}
}
func squareShearing<T>(matrix: inout [[T]],
coefficient: [[T]],
init_value: T,
multiply: (T, T) -> T,
add: (T, T) -> T) {
guard matrix.count > 0 && matrix.count == matrix[0].count else {
return
}
// 1 2 3 1 2 0 1 4 3
// 4 5 6 x 0 1 0 => 4 13 6
// 7 8 9 0 0 1 7 22 9
let ct = matrix.count
var res = [[T]](repeating: [T](repeating: init_value, count: ct), count: ct)
for row in 0..<matrix.count {
for col in 0..<matrix.count {
for n in 0..<matrix.count {
let product = multiply(matrix[row][n], coefficient[n][col])
res[row][col] = add(res[row][col], product)
}
}
}
matrix = res
}
}
|
code/graph_algorithms/src/maximum_bipartite_matching/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/maximum_bipartite_matching/maximum_bipartite_matching.py | # Part of Cosmos by OpenGenus Foundation
""" Python program to find maximal Bipartite matching.
This is taking corresponding to graph of applicants and
their corresponding job positions.
"""
class Graph:
def __init__(self, graph):
self.graph = graph # residual graph
self.ppl = len(graph)
self.jobs = len(graph[0])
# A DFS based recursive function that returns true if a
# matching for vertex u is possible
def bpm(self, u, matchR, seen):
# Try every job one by one
for v in range(self.jobs):
# If applicant u is interested in job v and v is
# not seen
if self.graph[u][v] and seen[v] == False:
seen[v] = True # Mark v as visited
"""If job 'v' is not assigned to an applicant OR
previously assigned applicant for job v (which is matchR[v])
has an alternate job available.
Since v is marked as visited in the above line, matchR[v]
in the following recursive call will not get job 'v' again"""
if matchR[v] == -1 or self.bpm(matchR[v], matchR, seen):
matchR[v] = u
return True
return False
# Returns maximum number of matching
def maxBPM(self):
"""An array to keep track of the applicants assigned to
jobs. The value of matchR[i] is the applicant number
assigned to job i, the value -1 indicates nobody is
assigned."""
matchR = [-1] * self.jobs
result = 0 # Count of jobs assigned to applicants
for i in range(self.ppl):
# Mark all jobs as not seen for next applicant.
seen = [False] * self.jobs
# Find if the applicant 'u' can get a job
if self.bpm(i, matchR, seen):
result += 1
return result
bpGraph = [
[0, 1, 1, 0, 0, 0],
[1, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
]
g = Graph(bpGraph)
print("Maximum matching number of applicants that can get job is %d " % g.maxBPM())
|
code/graph_algorithms/src/maximum_edge_disjoint_paths/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/minimum_s_t_cut/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/negative_cycle_finding/negativeCycleFinding.cpp | struct Edge {
ll a, b, cost;
};
int n, m;
vector<Edge> edges;
const ll INF = 1e9 + 5;
void solve(){
vector<ll> d(n);
vector<int> p(n, -1);
int x;
for (int i = 0; i < n; ++i) {
x = -1;
for (Edge e : edges) {
if (d[e.a] + e.cost < d[e.b]) {
d[e.b] = d[e.a] + e.cost;
p[e.b] = e.a;
x = e.b;
}
}
}
if (x == -1) {
cout << "NO\n";
} else {
for (int i = 0; i < n; ++i)
x = p[x];
vector<int> cycle;
for (int v = x;; v = p[v]) {
cycle.push_back(v);
if (v == x && cycle.size() > 1)
break;
}
reverse(cycle.begin(), cycle.end());
cout << "YES\n";
for (int v : cycle)
cout << v+1 << ' ';
cout << endl;
}
}
|
code/graph_algorithms/src/postorder_from_inorder_and_preorder/postorder_from_inorder_and_preorder.cpp | #include <iostream>
using namespace std;
int search(int in[], int k, int n)
{
for (int i = 0; i < n; i++)
if (in[i] == k)
return i;
return -1;
}
void postorder(int in[], int pre[], int n)
{
int root = search(in, pre[0], n);
if (root != 0)
postorder(in, pre + 1, root);
if (root != n - 1)
postorder(in + root + 1, pre + root + 1, n - root - 1);
cout << pre[0] << " ";
}
int main()
{
int in[] = {4, 2, 5, 1, 3, 6};
int pre[] = {1, 2, 4, 5, 3, 6};
int n = sizeof(in) / sizeof(in[0]);
cout << "Postorder traversal " << endl;
postorder(in, pre, n);
return 0;
}
|
code/graph_algorithms/src/prim_minimum_spanning_tree/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.c | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Single node of the graph
typedef struct node
{
int vert;
int weight;
struct node *next;
} node;
// Vertex of the graph
typedef struct vertex
{
int key;
int pos;
} vertex;
// Establish a connection of given weight
void connect(node *AdjList, int u, int v, int w)
{
node *new = (node *)malloc(sizeof(node));
new->vert = v;
new->weight = w;
node *t = AdjList + u;
new->next = t->next;
t->next = new;
}
// Function used to propagate heap changes to parent nodes
void heapify2(int heap[], vertex *v, int n, int i)
{
if(i == 0 || i >= n)
return;
if(v[heap[i]].key < v[heap[(i - 1) / 2]].key)
{
// Swap elements
int j = heap[i];
heap[i] = heap[(i - 1) / 2];
heap[(i - 1) / 2] = j;
// Correct positions
v[heap[i]].pos = i;
v[heap[(i - 1) / 2]].pos = (i - 1) / 2;
// Recurse
heapify2(heap, v, n, (i - 1) / 2);
}
}
// Main function used when creating heap
void heapify(int heap[], vertex *v, int n, int i)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int sm = i;
if(l < n && v[heap[sm]].key > v[heap[l]].key)
sm = l;
if(r < n && v[heap[sm]].key > v[heap[r]].key)
sm = r;
if(sm != i)
{
// Swap elements
int j = heap[i];
heap[i] = heap[sm];
heap[sm] = j;
// Correct positions
v[heap[i]].pos = i;
v[heap[sm]].pos = sm;
// Recurse
heapify(heap, v, n, sm);
}
}
// Remove an element from top of heap
int Hdel(int heap[], vertex *v, int *n)
{
int k = heap[0];
v[heap[0]].pos = -1;
heap[0] = heap[(*n) - 1];
v[heap[0]].pos = 0;
(*n)--;
heapify(heap, v, *n, 0);
return k;
}
// Main logic for Prim's Algorithm
void Prim(node *AdjList, int m, int n)
{
int i, tot = 0;
vertex *v = (vertex *)malloc(sizeof(vertex) * n);
int *heap = (int *)malloc(sizeof(int) * n);
// Create heap
for(i = 0; i < n; ++i)
{
v[i].key = INT_MAX;
v[i].pos = i;
heap[i] = i;
}
v[0].key = 0;
while(n > 0)
{
int vert = Hdel(heap, v, &n);
tot += v[vert].key;
node *t = AdjList[vert].next;
while(t != NULL)
{
if(v[t->vert].key > t->weight)
{
v[t->vert].key = t->weight;
heapify2(heap, v, n, v[t->vert].pos);
}
t = t->next;
}
}
printf("Weight of MST = %d\n", tot);
}
// Main function
int main()
{
// m = number of edges, n = number of vertices
int m = 8, n = 6;
node *AdjList;
AdjList = (node *)malloc(sizeof(node) * n);
/*
* Create edge connection
* Since graph is undirected,
* connections are formed in both
* directions
*/
connect(AdjList, 0, 1, 3);
connect(AdjList, 1, 0, 3);
connect(AdjList, 1, 4, 5);
connect(AdjList, 4, 1, 5);
connect(AdjList, 2, 3, 11);
connect(AdjList, 3, 2, 11);
connect(AdjList, 0, 4, 4);
connect(AdjList, 4, 0, 4);
connect(AdjList, 1, 2, 7);
connect(AdjList, 2, 1, 7);
connect(AdjList, 3, 5, 2);
connect(AdjList, 5, 3, 2);
connect(AdjList, 1, 5, 4);
connect(AdjList, 5, 1, 4);
connect(AdjList, 2, 4, 5);
connect(AdjList, 4, 2, 5);
Prim(AdjList, m, n);
return 0;
}
|
code/graph_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.cpp | #include <iostream>
#include <vector>
#include <utility>
#include <set>
using namespace std;
typedef long long ll;
// Part of Cosmos by OpenGenus Foundation
const int MAXN = 1e4 + 5;
bool vis[MAXN];
int n, m;
vector<pair<ll, int>> adj[MAXN]; // for every vertex store all the edge weight and the adjacent vertex to it
ll prim(int x)
{
// start prim from xth vertex
multiset<pair<int, int>> S; // multiset works same as minimum priority queue
ll minCost = 0;
S.insert({0, x});
while (!S.empty())
{
pair<int, int> p = *(S.begin());
S.erase(S.begin());
x = p.second;
if (vis[x])
continue;
minCost += p.first;
vis[x] = true;
for (size_t i = 0; i < adj[x].size(); i++)
{
int y = adj[x][i].second;
if (!vis[y])
S.insert(adj[x][i]);
}
}
return minCost;
}
int main()
{
cin >> n >> m; // n = number of vertices, m = number of edges
for (int i = 0; i < m; i++)
{
int x, y, weight;
cin >> x >> y >> weight;
adj[x].push_back({weight, y});
adj[y].push_back({weight, x});
}
// Selecting any node as the starting node
ll minCost = prim(1);
cout << minCost << endl;
return 0;
}
|
code/graph_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.py | # A Python program for Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix representation of the graph
# Part of Cosmos by OpenGenus Foundation
class Python:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
# Function to print the constructed MST stored in parent[]
def printMST(self, parent):
print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
# Function to find the vertex with minimum distance value, from
# the set of vertices not yet included in shortest path tree
def minKey(self, key, mstSet):
# Initilaize min value
min = 1000000
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
# Function to construct and print MST for a graph represented using
# adjacency matrix representation
def primMST(self):
# Key values used to pick minimum weight edge in cut
key = [1000000] * self.V
parent = [None] * self.V # Array to store constructed MST
key[0] = 0 # Make key 0 so that this vertex is picked as first vertex
mstSet = [False] * self.V
parent[0] = -1 # First node is always the root of
for cout in range(self.V):
# Pick the minimum distance vertex from the set of vertices not
# yet processed. u is always equal to src in first iteration
u = self.minKey(key, mstSet)
# Put the minimum distance vertex in the shortest path tree
mstSet[u] = True
# Update dist value of the adjacent vertices of the picked vertex
# only if the current distance is greater than new distance and
# the vertex in not in the shotest path tree
for v in range(self.V):
# graph[u][v] is non zero only for adjacent vertices of m
# mstSet[v] is false for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v]
if (
self.graph[u][v] > 0
and mstSet[v] == False
and key[v] > self.graph[u][v]
):
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
g = Python(5)
g.graph = [
[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0],
]
g.primMST()
|
code/graph_algorithms/src/push_relabel/push_relabel.cpp | #include <vector>
#include <queue>
// push as much excess flow as possible from f to t
void push(std::vector<std::vector<int>> graph, std::vector<std::vector<int>>& flow,
std::vector<std::vector<int>>& residual, std::vector<int>& excess, int f, int t)
{
if (excess[f] <= 0)
{
std::cerr << "excess on node " << f << "is " << excess[f] << "\n";
return;
}
// calculate the maximum amount of flow that can be pushed
int tmp = std::min(excess[f], residual[f][t]);
excess[f] -= tmp;
excess[t] += tmp;
residual[f][t] -= tmp;
residual[t][f] += tmp;
// if this holdes, the edge is a backwards edge, so t->f will be reduced
if (graph[f][t] == 0)
{
flow[t][f] -= tmp;
return;
}
flow[f][t] += tmp;
}
// reset the height of node "node", so excess flow can be pushed
void relabel(std::vector<std::vector<int>> residual, std::vector<int>& height, int node)
{
int min = std::numeric_limits<int>::max();
for (int i = 0; i < residual.size(); ++i)
if (residual[node][i] > 0 && height[i] < min)
min = height[i];
height[node] = min + 1;
}
// expecting propper flow matrix, empty residual and no a ->b, b-> a capacities
int maxFlowResidual(std::vector<std::vector<int>> graph, std::vector<std::vector<int>>& flow,
std::vector<std::vector<int>>& residual, int s, int t)
{
int numNodes = graph.size();
// property check
if (graph.size() != graph[0].size() || graph.size() != flow.size())
std::cerr << "Graph matrix/Flow Matrix has wrong format\n";
std::vector<int> excess(numNodes, 0);
excess[s] = std::numeric_limits<int>::max();
// initialize the residual graph
for (int i = 0; i < numNodes; ++i)
{
for (int j = 0; j < numNodes; ++j)
{
int tmp = flow[i][j];
if (tmp > 0)
residual[j][i] = tmp;
int g = graph[i][j] - tmp;
if (g > 0)
residual[i][j] = g;
}
}
std::queue<int> activeNodes;
// push initial flow from source
for (int i = 0; i < numNodes; ++i)
{
if (graph[s][i] > 0 && graph[s][i] > flow[s][i])
{
push(graph, flow, residual, excess, s, i);
activeNodes.push(i);
}
}
// create initial height values
std::vector<int> height(numNodes, 0);
height[s] = numNodes;
height[t] = 0;
while (!activeNodes.empty())
{
int node = activeNodes.front();
// store all nodes that excess flow can be pushed to from 'node'
std::vector<int> nbrList;
for (int i = 0; i < numNodes; ++i)
{
if (residual[node][i] > 0)
nbrList.push_back(i);
}
int i = 0;
// apply push / relabel to 'node' until all excess flow is taken care of
while (excess[node] > 0)
{
if (i == nbrList.size())
{
/*
* all possible neighbors have been visited but there is still too much incoming
* flow so the height of 'node' has to be increased
*/
i=0;
relabel(residual, height, node);
}
else
{
int j = nbrList[i];
if (residual[node][j] > 0 && height[node] > height[j])
{
push(graph, flow, residual, excess, node, j);
if (excess[j] > 0 && j != s && j != t)
activeNodes.push(j);
}
++i;
}
}
activeNodes.pop();
}
// extract the flow
int res = 0;
for (int i = 0; i < numNodes; ++i)
res += std::max(0, flow[s][i]);
return res;
}
int maxFlow(std::vector<std::vector<int>> graph,
std::vector<std::vector<int>>& flow, int s, int t)
{
int l = graph.size();
std::vector<std::vector<int>> emptyResidual(l, std::vector<int>(l, 0));
return maxFlowResidual(graph, flow, emptyResidual, s, t);
}
int maxFlowEmpty(std::vector<std::vector<int>> graph, int s, int t)
{
// create empty flow matrix
int l = graph.size();
std::vector<std::vector<int>> emptyFlow(l, std::vector<int>(l, 0));
return maxFlow(graph, emptyFlow, s, t);
}
|
code/graph_algorithms/src/redundant-connection/redundant_connection.cpp | /*
* Part of Cosmos by OpenGenus foundation
*
* Redundant Connection
*
* Description
*
* Return an edge that can be removed from an undirected graph so that the resulting graph is a tree of N nodes
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> parent; //disjoint set;
int findParent(int a)
{
if (parent[a] != a)
return parent[a] = findParent(parent[a]);
else
return a;
}
vector<int> findRedundantConnection(vector<vector<int>>& edges)
{
int n = edges.size();
parent.resize(n+1,0);
for(int i=0;i<=n;i++)
{
parent[i] = i;
}
vector<int> ans(2,0); //storing the answer
for(int i=0;i<n;i++)
{
int x = findParent(edges[i][0]); //Union Set
int y = findParent(edges[i][1]);
if(x != y)
parent[y] = x;
else
{
ans[0] = edges[i][0];
ans[1] = edges[i][1];
}
}
return ans;
}
int main ()
{
vector<vector<int>> edges;
int n , e;
cin >> n >> e;
cout << "Input number of vertices" << endl;
cout << "Input number of edges" << endl;
for(int i=0;i<e;i++)
{
int u , v; //temporary variables
vector<int> edge(2); //single edge
cin >> u >> v;
edge[0] = u;
edge[1] = v;
edges[i].push_back(edge);
}
cout << findRedundantConnection(edges);
return 0;
} |
code/graph_algorithms/src/shortest_path_k_edges/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/steiner_tree/steiner_tree.java | public class SteinerTree {
public static int minLengthSteinerTree(int[][] g, int[] verticesToConnect) {
int n = g.length;
int m = verticesToConnect.length;
if (m <= 1)
return 0;
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]);
int[][] dp = new int[1 << m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
dp[1 << i][j] = g[verticesToConnect[i]][j];
for (int i = 1; i < 1 << m; i++) {
if (((i - 1) & i) != 0) {
for (int j = 0; j < n; j++) {
dp[i][j] = Integer.MAX_VALUE / 2;
for (int k = (i - 1) & i; k > 0; k = (k - 1) & i) {
dp[i][j] = Math.min(dp[i][j], dp[k][j] + dp[i ^ k][j]);
}
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
dp[i][j] = Math.min(dp[i][j], dp[i][k] + g[k][j]);
}
}
}
}
return dp[(1 << m) - 1][verticesToConnect[0]];
}
}
|
code/graph_algorithms/src/strongly_connected_components/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/strongly_connected_components/strongly_connected_components.cpp | #include <iostream>
#include <list>
#include <stack>
using namespace std;
class Graph
{
int V; // No. of vertices
list<int> *adj; // An array of adjacency lists
// Fills Stack with vertices (in increasing order of finishing
// times). The top element of stack has the maximum finishing
// time
void fillOrder(int v, bool visited[], stack<int> &Stack);
// A recursive function to print DFS starting from v
void DFSUtil(int v, bool visited[]);
public:
Graph(int V);
void addEdge(int v, int w);
// The main function that finds and prints strongly connected
// components
void printSCCs();
// Function that returns reverse (or transpose) of this graph
Graph getTranspose();
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
// A recursive function to print DFS starting from v
void Graph::DFSUtil(int v, bool visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
cout << v << " ";
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFSUtil(*i, visited);
}
Graph Graph::getTranspose()
{
Graph g(V);
for (int v = 0; v < V; v++)
{
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
g.adj[*i].push_back(v);
}
return g;
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::fillOrder(int v, bool visited[], stack<int> &Stack)
{
// Mark the current node as visited and print it
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
fillOrder(*i, visited, Stack);
// All vertices reachable from v are processed by now, push v
Stack.push(v);
}
// The main function that finds and prints all strongly connected
// components
void Graph::printSCCs()
{
stack<int> Stack;
// Mark all the vertices as not visited (For first DFS)
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Fill vertices in stack according to their finishing times
for (int i = 0; i < V; i++)
if (visited[i] == false)
fillOrder(i, visited, Stack);
// Create a reversed graph
Graph gr = getTranspose();
// Mark all the vertices as not visited (For second DFS)
for (int i = 0; i < V; i++)
visited[i] = false;
// Now process all vertices in order defined by Stack
while (Stack.empty() == false)
{
// Pop a vertex from stack
int v = Stack.top();
Stack.pop();
// Print Strongly connected component of the popped vertex
if (visited[v] == false)
{
gr.DFSUtil(v, visited);
cout << endl;
}
}
}
int main()
{
Graph g(5);
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(3, 4);
cout << "Following are strongly connected components in "
"given graph \n";
g.printSCCs();
return 0;
}
|
code/graph_algorithms/src/strongly_connected_components/strongly_connected_components.py | # Part of Cosmos by Open Genus foundation
# Python implementation of Kosaraju's algorithm to print all SCCs
from collections import defaultdict
# This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self, vertices):
self.V = vertices # No. of vertices
self.graph = defaultdict(list) # default dictionary to store graph
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self, v, visited):
# Mark the current node as visited and print it
visited[v] = True
print(v, end=" ")
# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
def fillOrder(self, v, visited, stack):
# Mark the current node as visited
visited[v] = True
# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.fillOrder(i, visited, stack)
stack = stack.append(v)
# Function that returns reverse (or transpose) of this graph
def getTranspose(self):
g = Graph(self.V)
# Recur for all the vertices adjacent to this vertex
for i in self.graph:
for j in self.graph[i]:
g.addEdge(j, i)
return g
# The main function that finds and prints all strongly
# connected components
def printSCCs(self):
stack = []
# Mark all the vertices as not visited (For first DFS)
visited = [False] * (self.V)
# Fill vertices in stack according to their finishing
# times
for i in range(self.V):
if visited[i] == False:
self.fillOrder(i, visited, stack)
# Create a reversed graph
gr = self.getTranspose()
# Mark all the vertices as not visited (For second DFS)
visited = [False] * (self.V)
# Now process all vertices in order defined by Stack
while stack:
i = stack.pop()
if visited[i] == False:
gr.DFSUtil(i, visited)
print()
# Create a graph given in the above diagram
g = Graph(5)
g.addEdge(1, 0)
g.addEdge(0, 2)
g.addEdge(2, 1)
g.addEdge(0, 3)
g.addEdge(3, 4)
print("Following are strongly connected components " + "in given graph")
g.printSCCs()
|
code/graph_algorithms/src/tarjan_algorithm_strongly_connected_components/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/tarjan_algorithm_strongly_connected_components/tarjan_algorithm_strongly_connected_components.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Tarjan algorithm.
*
* You will need the data-structure located in
* https://github.com/OpenGenus/cosmos/tree/master/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C
* to use this algorithm.
*/
#include "lgraph_struct.h"
#include "lgraph_stack.h"
#include <stdio.h>
/* Deep course colors */
typedef enum
{
DC_WHITE = 0, /* The exploration of the node didn't start yet */
DC_GREY, /* The node is in exploration */
DC_BLACK /* The exploration of the node has ended */
} DC_Color;
/* The Tarjan algorithm needs those variables to mark nodes during deep course */
static LG_Stack lg_stackTarjan;
static Node_ID *nodesNums, *nodesAccessNums, currentNum;
/*
* Tarjan algorithm deep course subroutine.
* Deep course over node_ID & finds all the strongly connected components that can
* be found.
*
* @graph The directed graph.
* @node_ID ID of the origin node.
* @dc_colors Cur graph coloration.
* @connectedComps Strongly connected components array.
* @curComp Current strongly connected component ID.
*/
static void
tarjanAlgoDC(L_Graph* graph, Node_ID node_ID, DC_Color* dc_colors, size_t* sConnectedComps, size_t* curComp)
{
dc_colors[node_ID] = DC_GREY;
LG_StackPush(&lg_stackTarjan, node_ID);
nodesNums[node_ID] = currentNum;
nodesAccessNums[node_ID] = currentNum;
++currentNum;
OneEdge* edge = gNode_EdgesHead(gLG_Node(graph, node_ID));
while (edge != NULL) {
switch (dc_colors[gEdge_DestNode(edge)]) {
// A new node that hasn't yet a SCC
case DC_WHITE:
tarjanAlgoDC(graph, gEdge_DestNode(edge), dc_colors, sConnectedComps, curComp);
if (nodesAccessNums[gEdge_DestNode(edge)] < nodesAccessNums[node_ID])
nodesAccessNums[node_ID] = nodesAccessNums[gEdge_DestNode(edge)];
break;
// That node has already a SCC, we will see if we can merge.
case DC_GREY:
if (nodesAccessNums[gEdge_DestNode(edge)] < nodesAccessNums[node_ID])
nodesAccessNums[node_ID] = nodesAccessNums[gEdge_DestNode(edge)];
break;
default:
break;
}
edge = gEdgesList_Next(edge);
}
// Here, node_ID is the root of the strongly connected component
if (nodesNums[node_ID] == nodesAccessNums[node_ID]) {
Node_ID popNode;
do {
popNode = LG_StackPop(&lg_stackTarjan);
sConnectedComps[popNode] = *curComp;
} while(popNode != node_ID);
++(*curComp);
}
dc_colors[node_ID] = DC_BLACK;
}
/*
* For each node of the graph, stores in sConnectedComps the ID of its strongly connected
* component.
* This algorithm is the Tarjan Algorithm & executes in theta(S + A);
*
* @graph The directed graph.
* @sConnectedComps An array of at least |S| elements.
* @return Number of strongly connected components.
*/
int
tarjanAlgoConnectivity(L_Graph* graph, size_t* sConnectedComps)
{
DC_Color* dc_colors = calloc(gLG_NbNodes(graph), sizeof(*dc_colors));
Node_ID i;
size_t curComp = 0;
createLG_Stack(gLG_NbNodes(graph), &lg_stackTarjan);
nodesNums = malloc(sizeof(*nodesNums) * gLG_NbNodes(graph));
nodesAccessNums = malloc(sizeof(*nodesAccessNums) * gLG_NbNodes(graph));
currentNum = 0;
for (i = 0; i < gLG_NbNodes(graph); ++i) {
if (dc_colors[i] == DC_WHITE)
tarjanAlgoDC(graph, i, dc_colors, sConnectedComps, &curComp);
}
free(nodesAccessNums);
free(nodesNums);
freeLG_Stack(&lg_stackTarjan);
free(dc_colors);
return (curComp);
}
#define NB_NODES 5
int
main()
{
L_Graph g;
createLGraph(NB_NODES, &g);
LGraph_addDEdge(&g, 1, 3);
LGraph_addDEdge(&g, 2, 1);
LGraph_addDEdge(&g, 3, 4);
LGraph_addDEdge(&g, 4, 0);
LGraph_addDEdge(&g, 0, 3);
LGraph_addDEdge(&g, 1, 0);
size_t s[NB_NODES];
printf("%d\n\n", tarjanAlgoConnectivity(&g, s));
Node_ID i;
for (i = 0; i < NB_NODES; ++i)
printf("%d\n", s[i]);
freeLGraph(&g);
return (0);
}
|
code/graph_algorithms/src/topological_sort/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/topological_sort/kahn_algo_unique_toposort.cpp | // Sample problem for using this algorithm - UVA 11060 Beverages
#include <bits/stdc++.h>
#define all(a) a.begin(), a.end()
#define ll long long
#define inp(a) scanf("%d", &a)
#define out(a) printf("%d\n", a)
#define inp2(a) scanf("%lld", &a)
#define out2(a) printf("%lld\n", a)
#define arrinput(a, n) for (int i = 0; i < n; i++) scanf("%d", &a[i]);
#define pii pair<int, int>
#define piii pair<int, pair<int, int>>
#define vi vector<int>
#define rep(i, start, n) for (size_t i = start; i < static_cast<size_t>(n); i++)
#define pb push_back
#define F first
#define S second
#define mp make_pair
#define vb vector<bool>
#define testcases() int test; scanf("%d", &test); while (test--)
#define priorityqueue priority_queue<int, vector<int>, greater<int>>
#define minheappop(a) pop_heap(a.begin(), a.end(), compare); a.pop_back();
#define maxheappop(a) pop_heap(a.begin(), a.end()); a.pop_back();
#define minheappush(a, b) a.push_back(b); push_heap(a.begin(), a.end(), compare);
#define maxheappush(a, b) a.push_back(b); push_heap(a.begin(), a.end());
const int mod = 1000000007;
using namespace std;
map<string, vector<string>> graph;
map<string, int> inDegree;
vector<string> alcohols;
int n, m;
string u, v;
void kahnalgo()
{
set< pair<int, string >> q;
rep(i, 0, alcohols.size()) {
if (inDegree[alcohols[i]] == 0)
{
q.insert(mp(i, alcohols[i]));
inDegree[alcohols[i]] = -1;
}
}
while (q.size())
{
pair<int, string> cc = *q.begin();
string c = cc.S;
cout << " " << c;
q.erase(q.begin());
rep(i, 0, graph[c].size()) {
inDegree[graph[c][i]] -= 1;
}
rep(i, 0, alcohols.size()) {
if (inDegree[alcohols[i]] == 0)
{
q.insert(mp(i, alcohols[i]));
inDegree[alcohols[i]] = -1;
}
}
}
}
int main()
{
int cases = 0;
while (inp(n) != EOF)
{
cases += 1;
inDegree.clear();
graph.clear();
alcohols.clear();
rep(i, 0, n) {
cin >> u;
alcohols.pb(u);
graph[u] = vector<string>();
}
inp(m);
rep(i, 0, m) {
cin >> u >> v;
inDegree[v] += 1;
graph[u].pb(v);
}
printf("Case #%d: Dilbert should drink beverages in this order:", cases);
kahnalgo();
printf(".\n\n");
getchar();
}
return 0;
}
|
code/graph_algorithms/src/topological_sort/kahn_algorithm_basic.cpp | /*
* Implementation of the Kahn's algorithm
* for topological sort in a directed acyclic graph
*/
#include <iostream>
#include "bits/stdc++.h"
using namespace std;
queue<int> q, q2;
long long n = 100000;
int v, e, v1, v2, visited[10000], level[100000], indegree[100000];
vector<int> g[100000];
void bfs(int i)
{
while (!q.empty())
{
for (int j = 0; j < g[q.front()].size(); j++)
{
indegree[g[q.front()][j]]--;
}
for (int j = 0; j < g[q.front()].size(); j++)
{
if (visited[g[q.front()][j]] != 1)
{
if (indegree[g[q.front()][j]] == 0)
{
q.push(g[q.front()][j]);
visited[g[q.front()][j]] = 1;
}
}
}
cout << q.front() << " ";
q.pop();
}
}
int main()
{
int v, e, v1, v2;
cin >> v >> e;
g[v + 1].resize(v + 1);
for (int i = 0; i < e; i++)
{
cin >> v1 >> v2;
g[v1].push_back(v2);
indegree[v2]++;
}
cout << "Nodes and indegrees\n";
for (int i = 1; i <= v; i++)
{
cout << i << " " << indegree[i] << endl;
}
cout << "Topological sort order :";
for (int i = 1; i < v + 1; i++)
if (indegree[i] == 0)
{
q.push(i);
visited[i] = 1;
}
bfs(1);
cout << endl;
}
|
code/graph_algorithms/src/topological_sort/print_all_topological_sorts.cpp | #include <iostream>
#include <vector>
using namespace std;
class Graph {
vector<vector<int>> graph;
vector<int> indegree;
public:
Graph (int);
void insert_egde (int, int);
void all_topo_sorts ();
void all_topo_sorts_helper (vector<int> &, vector<bool> &);
};
Graph :: Graph (int v)
{
graph.resize (v);
indegree.resize (v);
}
void Graph :: insert_egde (int s, int d)
{
graph[s].push_back (d);
indegree[d]++;
}
void Graph :: all_topo_sorts ()
{
vector<int> topo;
vector<bool> visited (graph.size());
all_topo_sorts_helper (topo, visited);
}
void Graph :: all_topo_sorts_helper (vector<int> & topo, vector<bool> & visited)
{
for (std::size_t i = 0; i < graph.size(); i++)
if (indegree[i] == 0 && !visited[i])
{
for (auto j : graph[i]) // reduce indegree of outgoing vertices
indegree[j]--;
topo.push_back (i); // visit this vertex
visited[i] = true;
all_topo_sorts_helper (topo, visited); // recursively call this method; for all vertices which come after this one in the topological sort
visited[i] = false; // now backtracking
topo.erase (topo.end() - 1);
for (auto j : graph[i])
indegree[j]++;
}
if (topo.size() == graph.size())
{
for (std::size_t i = 0; i < topo.size(); i++)
cout << topo[i] << " ";
cout << endl;
}
}
int main()
{
int v, e, s, d;
cout << "Enter number of vertices and edges : ";
cin >> v >> e;
Graph g (v);
cout << "Enter the edges :\n";
for (int i = 0; i < e; i++)
{
cin >> s >> d;
g.insert_egde (s, d);
}
cout << "The topological sorts are : \n";
g.all_topo_sorts();
return 0;
}
|
code/graph_algorithms/src/topological_sort/topological_sort.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Topological sort based on depth-first search.
*
* You will need the data-structure located in
* https://github.com/OpenGenus/cosmos/tree/master/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C
* to use this algorithm.
*/
#include <stdio.h>
#include "lgraph_struct.h"
/* Deep course colors */
typedef enum
{
DC_WHITE, /* The exploration of the node didn't start yet */
DC_GREY, /* The node is in exploration */
DC_BLACK /* The exploration of the node has ended */
} DC_Color;
/*
* Deep course subroutine of topological sort.
* Sorts nodes that are accessible via node_ID.
*
* @graph The graph.
* @node_ID Node to loop over.
* @dc_colors Cur coloration of the graph.
* @sortedNodes The array that stores sorted nodes.
* @sortedCurPos Pointer to the current position in sortedNodes.
* @return -1 if can't get a topological sort, 0 otherwise.
*/
static int
topoSortDC(L_Graph* graph, Node_ID node_ID, DC_Color* dc_colors, Node_ID* sortedNodes, int* sortedCurPos)
{
dc_colors[node_ID] = DC_GREY;
OneEdge* edge = gNode_EdgesHead(gLG_Node(graph, node_ID));
while (edge != NULL) {
switch (dc_colors[gEdge_DestNode(edge)]) {
case DC_WHITE:
if(topoSortDC(graph, gEdge_DestNode(edge), dc_colors, sortedNodes, sortedCurPos) == -1)
return (-1); /* Rear arc */
break;
/* Rear arc found, the graph has a directed cycle, can't get a topologial sort */
case DC_GREY:
return (-1);
break;
default:
break;
}
edge = gEdgesList_Next(edge);
}
dc_colors[node_ID] = DC_BLACK;
sortedNodes[*sortedCurPos] = node_ID;
--(*sortedCurPos);
return (0);
}
/*
* Let G = (S, A)
* Executes a topological sort on G in thêta(S + A).
* The result is stored in sortedNodes. It must be an array that has at least
* |S| elements.
*
* @graph The graph. It musn't have a directed cycle.
* @sortedNodes An array of at least |S| elements. It will store the result.
* @return 0 on success, -1 if the graph has a directed cycle.
*/
int
topologicalSort(L_Graph* graph, Node_ID* sortedNodes)
{
DC_Color* dc_colors = calloc(gLG_NbNodes(graph), sizeof(*dc_colors));
Node_ID i;
int sortedCurPos = gLG_NbNodes(graph) - 1;
for (i = 0; i < gLG_NbNodes(graph); ++i) {
if (dc_colors[i] == DC_WHITE && topoSortDC(graph, i, dc_colors, sortedNodes, &sortedCurPos) == -1) {
free(dc_colors);
return (-1);
}
}
free(dc_colors);
return (0);
}
#define S 5
int
main()
{
L_Graph g;
createLGraph(S, &g);
LGraph_addDEdge(&g, 0, 1);
LGraph_addDEdge(&g, 1, 2);
LGraph_addDEdge(&g, 3, 4);
LGraph_addDEdge(&g, 4, 2);
size_t s[S];
printf("%d\n\n", topologicalSort(&g, s));
int i;
for (i = 0; i < S; ++i)
printf("%d\n", s[i]);
freeLGraph(&g);
return (0);
}
|
code/graph_algorithms/src/topological_sort/topological_sort.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define NUM_V 100005
vector<int> adjList[NUM_V + 5];
int inDegree[NUM_V + 5];
int vertex;
vector<int> toposort()
{
vector<int> result;
queue<int> q;
for (int i = 1; i <= vertex; i++)
// if no incoming degree, add to queue
if (inDegree[i] == 0)
q.push(i);
while (!q.empty())
{
int front = q.front();
q.pop();
// add into toposort result
result.push_back(front);
for (size_t i = 0; i < adjList[front].size(); i++)
{
int neighbor = adjList[front][i];
inDegree[neighbor]--;
// if already no incoming degree, then ready to put in toposort list
if (inDegree[neighbor] == 0)
q.push(neighbor);
}
}
return result;
}
int main()
{
/* consider following graph
* 1----->2----->5
* | ^^
* | / |
* | / |
* | / |
* v / |
* 4----->3
* one of the solution would be
* 1 -> 4 -> 3 -> 2 -> 5
*/
vertex = 5;
adjList[1].push_back(2);
adjList[1].push_back(4);
adjList[2].push_back(5);
adjList[3].push_back(2);
adjList[4].push_back(2);
adjList[4].push_back(3);
inDegree[1] = 0;
inDegree[2] = 3;
inDegree[3] = 1;
inDegree[4] = 1;
inDegree[5] = 1;
vector<int> toposortResult = toposort();
printf("toposort :");
for (size_t i = 0; i < toposortResult.size(); i++)
printf(" %d", toposortResult[i]);
printf("\n");
}
|
code/graph_algorithms/src/topological_sort/topological_sort.hs | module Topological where
import Data.List
-- Part of Cosmos by OpenGenus
-- Note: this implementation is not the most efficient.
-- With a better DAG datastructure, this would be O(V+E)
-- But if the number of sources of the graph is generally low,
-- this implementation approximates that.
topo' [] _ _ = []
topo' (r:rs) graph nodes = r : (topo' (rs ++ newRoots) graph' nodes')
where
nodes' = delete r nodes
graph' = filter (\(a, b) -> a /= r) graph
newRoots = filter (\n -> not (n `elem` rs)
&& all (\(a, b) -> b /= n) graph') nodes'
topo relation list = topo' roots graph nodes
where
roots = filter (\n -> all (\(a, b) -> b /= n) graph) nodes
graph = [(a,b) | a <- list, b <- list, a /= b, a `relation` b]
nodes = (nub list)
main = print $ [200,199..1] == topo (>=) [1..200]
|
code/graph_algorithms/src/topological_sort/topological_sort.js | /**
* Part of Cosmos by OpenGenus
* Javascript program to find topological Sort order of a Directed Acyclic Graph.
* Topological sorting for Directed Acyclic Graph (DAG) is a linear
* ordering ofvertices such that for every directed edge uv,1
* vertex u comes before v in the ordering.
*/
class Graph {
constructor(noOfVertices) {
this.V = noOfVertices;
this.graph = Array(noOfVertices)
.fill([])
.map(a => a.slice());
this.topSortOrder = [];
}
addEdge(u, v) {
this.graph[u].push(v);
}
printSolution() {
console.log("The Topological Sort Order of the given graph is: ");
console.log(this.topSortOrder.slice(0, this.V - 1));
}
topologicalSortUtil(v, visited) {
visited[v] = true;
for (const i of this.graph[v]) {
if (visited[i] === false) {
this.topologicalSortUtil(i, visited);
}
}
this.topSortOrder.unshift(v); // insert element at the beginning
}
topologicalSort() {
let visited = Array(this.V).fill(false);
for (let i = 0; i < this.V; i++) {
if (visited[i] === false) {
this.topologicalSortUtil(i, visited);
}
}
this.printSolution();
}
}
g = new Graph(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
g.topologicalSort();
|
code/graph_algorithms/src/topological_sort/topological_sort.py | """ Part of Cosmos by OpenGenus Foundation """
from collections import deque
NUM_V = 100005
adj_list = [[] for i in range(0, NUM_V)]
in_degree = [0 for i in range(0, NUM_V)]
def toposort():
result = []
q = deque()
for i in range(1, vertex + 1):
# if no incoming degree, add to queue
if in_degree[i] == 0:
q.append(i)
while q:
front = q.popleft()
# add into toposort result
result.append(front)
for neighbor in adj_list[front]:
in_degree[neighbor] -= 1
# if already no incoming degree, then ready to put in toposort list
if in_degree[neighbor] == 0:
q.append(neighbor)
return result
"""
consider following graph
1----->2----->5
| ^^
| / |
| / |
| / |
v / |
4----->3
one of the solution would be
1 -> 4 -> 3 -> 2 -> 5
"""
vertex = 5
adj_list[1].append(2)
adj_list[1].append(4)
adj_list[2].append(5)
adj_list[3].append(2)
adj_list[4].append(2)
adj_list[4].append(3)
in_degree[1] = 0
in_degree[2] = 3
in_degree[3] = 1
in_degree[4] = 1
in_degree[5] = 1
result = toposort()
print("toposort :", end="")
for vtx in result:
print(" {:d}".format(vtx), end="")
print()
|
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_list.java | /**
* This topological sort implementation takes an adjacency list of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering 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.
*
* Time Complexity: O(V + E)
*
* @author William Fiset, [email protected]
**/
import java.util.*;
// Helper Edge class to describe edges in the graph
class Edge {
int from, to, weight;
public Edge (int f, int t, int w) {
from = f; to = t; weight = w;
}
}
public class TopologicalSortAdjacencyList {
// Helper method that performs a depth first search on the graph to give
// us the topological ordering we want. Instead of maintaining a stack
// of the nodes we see we simply place them inside the ordering array
// in reverse order for simplicity.
private static int dfs(int i, int at, boolean[] visited, int[] ordering, Map<Integer, List<Edge>> graph) {
visited[at] = true;
List<Edge> edges = graph.get(at);
if (edges != null)
for (Edge edge : edges)
if (!visited[edge.to])
i = dfs(i, edge.to, visited, ordering, graph);
ordering[i] = at;
return i-1;
}
// Finds a topological ordering of the nodes in a Directed Acyclic Graph (DAG)
// The input to this function is an adjacency list for a graph and the number
// of nodes in the graph.
//
// NOTE: 'numNodes' is not necessarily the number of nodes currently present
// in the adjacency list since you can have singleton nodes with no edges which
// wouldn't be present in the adjacency list but are still part of the graph!
//
public static int[] topologicalSort(Map<Integer, List<Edge>> graph, int numNodes) {
int[] ordering = new int[numNodes];
boolean[] visited = new boolean[numNodes];
int i = numNodes - 1;
for (int at = 0; at < numNodes; at++)
if (!visited[at])
i = dfs(i, at, visited, ordering, graph);
return ordering;
}
// A useful application of the topological sort is to find the shortest path
// between two nodes in a Directed Acyclic Graph (DAG). Given an adjacency matrix
// this method finds the shortest path to all nodes starting at 'start'
//
// NOTE: 'numNodes' is not necessarily the number of nodes currently present
// in the adjacency list since you can have singleton nodes with no edges which
// wouldn't be present in the adjacency list but are still part of the graph!
//
public static Integer[] dagShortestPath(Map<Integer, List<Edge>> graph, int start, int numNodes) {
int[] topsort = topologicalSort(graph, numNodes);
Integer[] dist = new Integer[numNodes];
dist[start] = 0;
for(int i = 0; i < numNodes; i++) {
int nodeIndex = topsort[i];
if (dist[nodeIndex] != null) {
List<Edge> adjacentEdges = graph.get(nodeIndex);
if (adjacentEdges != null) {
for (Edge edge : adjacentEdges) {
int newDist = dist[nodeIndex] + edge.weight;
if (dist[edge.to] == null) dist[edge.to] = newDist;
else dist[edge.to] = Math.min(dist[edge.to], newDist);
}
}
}
}
return dist;
}
// Example usage of topological sort
public static void main(String[] args) {
// Graph setup
final int N = 7;
Map<Integer, List<Edge>> graph = new HashMap<>();
for (int i = 0; i < N; i++) graph.put(i, new ArrayList<>());
graph.get(0).add(new Edge(0,1,3));
graph.get(0).add(new Edge(0,2,2));
graph.get(0).add(new Edge(0,5,3));
graph.get(1).add(new Edge(1,3,1));
graph.get(1).add(new Edge(1,2,6));
graph.get(2).add(new Edge(2,3,1));
graph.get(2).add(new Edge(2,4,10));
graph.get(3).add(new Edge(3,4,5));
graph.get(5).add(new Edge(5,4,7));
int[] ordering = topologicalSort(graph, N);
// // Prints: [6, 0, 5, 1, 2, 3, 4]
System.out.println(java.util.Arrays.toString(ordering));
// Finds all the shortest paths starting at node 0
Integer[] dists = dagShortestPath(graph, 0, N);
// Find the shortest path from 0 to 4 which is 8.0
System.out.println(dists[4]);
// Find the shortest path from 0 to 6 which
// is null since 6 is not reachable!
System.out.println(dists[6]);
}
}
|
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_list2.java | /**
* This topological sort implementation takes an adjacency list of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering 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.
*
* Time Complexity: O(V + E)
*
* @author William Fiset, [email protected]
**/
import java.util.*;
// Helper Edge class to describe edges in the graph
class Edge {
int from, to, weight;
public Edge (int f, int t, int w) {
from = f; to = t; weight = w;
}
}
public class TopologicalSortAdjacencyList {
// Helper method that performs a depth first search on the graph to give
// us the topological ordering we want. Instead of maintaining a stack
// of the nodes we see we simply place them inside the ordering array
// in reverse order for simplicity.
private static int dfs(int i, int at, boolean[] visited, int[] ordering, Map<Integer, List<Edge>> graph) {
visited[at] = true;
List<Edge> edges = graph.get(at);
if (edges != null)
for (Edge edge : edges)
if (!visited[edge.to])
i = dfs(i, edge.to, visited, ordering, graph);
ordering[i] = at;
return i-1;
}
// Finds a topological ordering of the nodes in a Directed Acyclic Graph (DAG)
// The input to this function is an adjacency list for a graph and the number
// of nodes in the graph.
//
// NOTE: 'numNodes' is not necessarily the number of nodes currently present
// in the adjacency list since you can have singleton nodes with no edges which
// wouldn't be present in the adjacency list but are still part of the graph!
//
public static int[] topologicalSort(Map<Integer, List<Edge>> graph, int numNodes) {
int[] ordering = new int[numNodes];
boolean[] visited = new boolean[numNodes];
int i = numNodes - 1;
for (int at = 0; at < numNodes; at++)
if (!visited[at])
i = dfs(i, at, visited, ordering, graph);
return ordering;
}
// A useful application of the topological sort is to find the shortest path
// between two nodes in a Directed Acyclic Graph (DAG). Given an adjacency matrix
// this method finds the shortest path to all nodes starting at 'start'
//
// NOTE: 'numNodes' is not necessarily the number of nodes currently present
// in the adjacency list since you can have singleton nodes with no edges which
// wouldn't be present in the adjacency list but are still part of the graph!
//
public static Integer[] dagShortestPath(Map<Integer, List<Edge>> graph, int start, int numNodes) {
int[] topsort = topologicalSort(graph, numNodes);
Integer[] dist = new Integer[numNodes];
dist[start] = 0;
for(int i = 0; i < numNodes; i++) {
int nodeIndex = topsort[i];
if (dist[nodeIndex] != null) {
List<Edge> adjacentEdges = graph.get(nodeIndex);
if (adjacentEdges != null) {
for (Edge edge : adjacentEdges) {
int newDist = dist[nodeIndex] + edge.weight;
if (dist[edge.to] == null) dist[edge.to] = newDist;
else dist[edge.to] = Math.min(dist[edge.to], newDist);
}
}
}
}
return dist;
}
// Example usage of topological sort
public static void main(String[] args) {
// Graph setup
final int N = 7;
Map<Integer, List<Edge>> graph = new HashMap<>();
for (int i = 0; i < N; i++) graph.put(i, new ArrayList<>());
graph.get(0).add(new Edge(0,1,3));
graph.get(0).add(new Edge(0,2,2));
graph.get(0).add(new Edge(0,5,3));
graph.get(1).add(new Edge(1,3,1));
graph.get(1).add(new Edge(1,2,6));
graph.get(2).add(new Edge(2,3,1));
graph.get(2).add(new Edge(2,4,10));
graph.get(3).add(new Edge(3,4,5));
graph.get(5).add(new Edge(5,4,7));
int[] ordering = topologicalSort(graph, N);
// // Prints: [6, 0, 5, 1, 2, 3, 4]
System.out.println(java.util.Arrays.toString(ordering));
// Finds all the shortest paths starting at node 0
Integer[] dists = dagShortestPath(graph, 0, N);
// Find the shortest path from 0 to 4 which is 8.0
System.out.println(dists[4]);
// Find the shortest path from 0 to 6 which
// is null since 6 is not reachable!
System.out.println(dists[6]);
}
}
|
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_matrix.java | /**
* This Topological sort takes an adjacency matrix of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering 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.
*
* Time Complexity: O(V^2)
*
* @author Micah Stairs
**/
public class TopologicalSortAdjacencyMatrix {
// Performs the topological sort and returns the
// indexes of the nodes in topological order
public static int[] topologicalSort(Double[][] adj) {
// Setup
int n = adj.length;
boolean[] visited = new boolean[n];
int[] order = new int[n];
int index = n - 1;
// Visit each node
for (int u = 0; u < n; u++)
if (!visited[u])
index = visit(adj, visited, order, index, u);
// Return topological sort
return order;
}
private static int visit(Double[][] adj, boolean[] visited, int[] order, int index, int u) {
if (visited[u]) return index;
visited[u] = true;
// Visit all neighbors
for (int v = 0; v < adj.length; v++)
if (adj[u][v] != null && !visited[v])
index = visit(adj, visited, order, index, v);
// Place this node at the head of the list
order[index--] = u;
return index;
}
// A useful application of the topological sort is to find the shortest path
// between two nodes in a Directed Acyclic Graph (DAG). Given an adjacency matrix
// with double valued edge weights this method finds the shortest path from
// a start node to all other nodes in the graph.
public static double[] dagShortestPath(Double[][] adj, int start) {
// Set up array used to maintain minimum distances from start
int n = adj.length;
double[] dist = new double[n];
java.util.Arrays.fill(dist, Double.POSITIVE_INFINITY);
dist[start] = 0.0;
// Process nodes in a topologically sorted order
for (int u: topologicalSort(adj))
for (int v = 0; v < n; v++) {
if (adj[u][v] != null) {
double newDist = dist[u] + adj[u][v];
if (newDist < dist[v])
dist[v] = newDist;
}
}
// Return minimum distance
return dist;
}
// Example usage of topological sort
public static void main(String[] args) {
final int N = 7;
Double[][] adjMatrix = new Double[N][N];
adjMatrix[0][1] = 3.0;
adjMatrix[0][2] = 2.0;
adjMatrix[0][5] = 3.0;
adjMatrix[1][3] = 1.0;
adjMatrix[1][2] = 6.0;
adjMatrix[2][3] = 1.0;
adjMatrix[2][4] = 10.0;
adjMatrix[3][4] = 5.0;
adjMatrix[5][4] = 7.0;
int[] ordering = topologicalSort(adjMatrix);
// Prints: [6, 0, 5, 1, 2, 3, 4]
System.out.println(java.util.Arrays.toString(ordering));
// Find the shortest path from 0 to all other nodes
double [] dists = dagShortestPath(adjMatrix, 0);
// Find the distance from 0 to 4 which is 8.0
System.out.println(dists[4]);
// Finds the shortest path from 0 to 6
// prints Infinity (6 is not reachable!)
System.out.println(dists[6]);
}
}
|
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_matrix2.java | /**
* This Topological sort takes an adjacency matrix of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering 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.
*
* Time Complexity: O(V^2)
*
* @author Micah Stairs
**/
public class TopologicalSortAdjacencyMatrix {
// Performs the topological sort and returns the
// indexes of the nodes in topological order
public static int[] topologicalSort(Double[][] adj) {
// Setup
int n = adj.length;
boolean[] visited = new boolean[n];
int[] order = new int[n];
int index = n - 1;
// Visit each node
for (int u = 0; u < n; u++)
if (!visited[u])
index = visit(adj, visited, order, index, u);
// Return topological sort
return order;
}
private static int visit(Double[][] adj, boolean[] visited, int[] order, int index, int u) {
if (visited[u]) return index;
visited[u] = true;
// Visit all neighbors
for (int v = 0; v < adj.length; v++)
if (adj[u][v] != null && !visited[v])
index = visit(adj, visited, order, index, v);
// Place this node at the head of the list
order[index--] = u;
return index;
}
// A useful application of the topological sort is to find the shortest path
// between two nodes in a Directed Acyclic Graph (DAG). Given an adjacency matrix
// with double valued edge weights this method finds the shortest path from
// a start node to all other nodes in the graph.
public static double[] dagShortestPath(Double[][] adj, int start) {
// Set up array used to maintain minimum distances from start
int n = adj.length;
double[] dist = new double[n];
java.util.Arrays.fill(dist, Double.POSITIVE_INFINITY);
dist[start] = 0.0;
// Process nodes in a topologically sorted order
for (int u: topologicalSort(adj))
for (int v = 0; v < n; v++) {
if (adj[u][v] != null) {
double newDist = dist[u] + adj[u][v];
if (newDist < dist[v])
dist[v] = newDist;
}
}
// Return minimum distance
return dist;
}
// Example usage of topological sort
public static void main(String[] args) {
final int N = 7;
Double[][] adjMatrix = new Double[N][N];
adjMatrix[0][1] = 3.0;
adjMatrix[0][2] = 2.0;
adjMatrix[0][5] = 3.0;
adjMatrix[1][3] = 1.0;
adjMatrix[1][2] = 6.0;
adjMatrix[2][3] = 1.0;
adjMatrix[2][4] = 10.0;
adjMatrix[3][4] = 5.0;
adjMatrix[5][4] = 7.0;
int[] ordering = topologicalSort(adjMatrix);
// Prints: [6, 0, 5, 1, 2, 3, 4]
System.out.println(java.util.Arrays.toString(ordering));
// Find the shortest path from 0 to all other nodes
double [] dists = dagShortestPath(adjMatrix, 0);
// Find the distance from 0 to 4 which is 8.0
System.out.println(dists[4]);
// Finds the shortest path from 0 to 6
// prints Infinity (6 is not reachable!)
System.out.println(dists[6]);
}
}
|
code/graph_algorithms/src/transitive_closure_graph/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph.cpp | #include <stdio.h>
#include <iostream>
using namespace std;
void printSolution(int reach[][4])
{
cout << "Following matrix is transitive closure of the given graph\n";
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
cout << reach[i][j];
cout << endl;
}
}
void transitiveClosure(int graph[][4])
{
int reach[4][4], i, j, k;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
reach[i][j] = graph[i][j];
for (k = 0; k < 4; k++)
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
printSolution(reach);
}
int main()
{
int graph[4][4] = { {1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};
transitiveClosure(graph);
}
|
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph.py | # Python program to print transitive closure of a graph
# Part of Cosmos by OpenGenus Foundation
from collections import defaultdict
# This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self, vertices):
# No. of vertices
self.V = vertices
# default dictionary to store graph
self.graph = defaultdict(list)
# To store transitive closure
self.tc = [[0 for j in range(self.V)] for i in range(self.V)]
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A recursive DFS traversal function that finds
# all reachable vertices for s
def DFSUtil(self, s, v):
# Mark reachability from s to v as true.
self.tc[s][v] = 1
# Find all the vertices reachable through v
for i in self.graph[v]:
if self.tc[s][i] == 0:
self.DFSUtil(s, i)
# The function to find transitive closure. It uses
# recursive DFSUtil()
def transitiveClosure(self):
# Call the recursive function to print DFS
# traversal starting from all vertices one by one
for i in range(self.V):
self.DFSUtil(i, i)
print(self.tc)
# Create a graph
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Transitive closure matrix is")
g.transitiveClosure()
|
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph_floyd_warshall.cpp | #include <iostream>
#include <vector>
#include <bitset>
/* Part of Cosmos by OpenGenus Foundation */
// Floyd-Warshall algorithm. Time complexity: O(n ^ 3)
void transitive_closure_graph(std::vector<std::vector<int>> &graph)
{
int n = (int) graph.size();
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
graph[i][j] |= (graph[i][k] & graph[k][j]);
}
const int MAX_N = 2000; // maximum possible number of vertixes (only for bitset version)
// Floyd-Warshall algorithm with bitset.
// Time complexity: O(n ^ 3), but with 1/bitset constant. (~32 or ~64 times faster than naive)
void transitive_closure_graph_bitset(std::vector<std::vector<int>> &graph)
{
int n = (int) graph.size();
std::vector<std::bitset<MAX_N>> d(n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
d[i][j] = graph[i][j];
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
if (d[i][k])
d[i] |= d[k];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
graph[i][j] = d[i][j];
}
int main()
{
std::cout << "Enter the number of vertexes:" << std::endl;
int n;
std::cin >> n;
std::cout << "Enter the adjacency matrix (consisting from 0 and 1):" << std::endl;
std::vector<std::vector<int>> graph(n, std::vector<int>(n));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cin >> graph[i][j];
transitive_closure_graph_bitset(graph);
std::cout << "Result:\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
std::cout << graph[i][j] << " ";
std::cout << "\n";
}
return 0;
}
|
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph_powering.cpp | #include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
/// utility function to print the transitive closure matrix
void print_transitive_closure(int** output, int num_nodes)
{
cout << endl;
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout << output[i][j] << " ";
}
cout << endl;
}
}
/// utility function to convert powering matrix to transitive closure matrix
void transitive_closure(int** matrix, int num_nodes)
{
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
if(matrix[i][j]>0)
{
matrix[i][j] = 1;
}
}
}
print_transitive_closure(matrix,num_nodes);
}
/// utility function to power the matrix
void matrix_powering(int** edges_list,int num_nodes)
{
int result[num_nodes][num_nodes];
int** matrix = new int*[num_nodes];
for(int i=0;i<num_nodes;i++)
{
matrix[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
matrix[i][j] = edges_list[i][j];
}
}
int sum = 0;
for (int i = 0; i < num_nodes; i++)
{
for ( int c = 0 ; c < num_nodes ; c++ )
{
for (int d = 0 ; d < num_nodes ; d++ )
{
for (int k = 0 ; k < num_nodes ; k++ )
{
sum += matrix[c][k]*matrix[k][d];
}
result[c][d] = sum;
sum = 0;
}
}
for ( int c = 0 ; c < num_nodes ; c++ ) {
for ( int d = 0 ; d < num_nodes ; d++ ) {
matrix[c][d] = result[c][d];
result[c][d] = 0;
}
}
}
transitive_closure(matrix,num_nodes);
}
int main()
{
int num_nodes,num_edges;
cin >> num_nodes >> num_edges;
int** edges_list = new int*[num_nodes];
for(int i=0;i<num_nodes;i++)
{
edges_list[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
edges_list[i][j] = 0;
}
}
for(int i=0;i<num_edges;i++)
{
int first_node,second_node;
cin >> first_node >> second_node;
edges_list[first_node][second_node] = 1;
if(i<num_nodes)
edges_list[i][i]=1;
}
cout << "Input Adjacent Matrix Graph:" << endl;
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout << edges_list[i][j] << " ";
}
cout << endl;
}
matrix_powering(edges_list,num_nodes);
return 0;
}
|
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph_powering_improved.cpp | #include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
/// utility function to print the transitive closure matrix
void print_transitive_closure(int** output, int num_nodes)
{
cout << endl;
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout << output[i][j] << " ";
}
cout << endl;
}
}
/// utility function to convert powering matrix to transitive closure matrix
void transitive_closure(int** matrix, int num_nodes)
{
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
if(matrix[i][j]>0)
{
matrix[i][j] = 1;
}
}
}
print_transitive_closure(matrix,num_nodes);
}
/// utility function to get the identity matrix
void identity_matrix(int** a, int SIZE)
{
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
a[i][j] = (i == j);
}
//matrix_multiplication method
void matrix_multiplication(int** a, int** b,int SIZE)
{
int** res = new int*[SIZE];
for(int i=0;i<SIZE;i++)
{
res[i] = new int[SIZE];
for(int j=0;j<SIZE;j++)
{
res[i][j] = 0;
}
}
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
for (int k = 0; k < SIZE; k++)
{
res[i][j] += a[i][k] * b[k][j];
}
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
a[i][j] = res[i][j];
}
// matrix powering to nth power
void matrix_powering(int** a, int n, int** res,int num_nodes)
{
identity_matrix(res,num_nodes);
while (n > 0) {
if (n % 2 == 0)
{
matrix_multiplication(a, a,num_nodes);
n /= 2;
}
else {
matrix_multiplication(res, a,num_nodes);
n--;
}
}
transitive_closure(res,num_nodes);
}
int main()
{
int num_nodes,num_edges;
cin >> num_nodes >> num_edges;
int** edges_list = new int*[num_nodes];
for(int i=0;i<num_nodes;i++)
{
edges_list[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
edges_list[i][j] = 0;
}
}
for(int i=0;i<num_edges;i++)
{
int first_node,second_node;
cin >> first_node >> second_node;
edges_list[first_node][second_node] = 1;
if(i<num_nodes)
edges_list[i][i]=1;
}
cout << "Input Adjacent Matrix Graph:" << endl;
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout << edges_list[i][j] << " ";
}
cout << endl;
}
int** result = new int*[num_nodes];
for(int i=0;i<num_nodes;i++)
{
result[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
result[i][j] = 0;
}
}
matrix_powering(edges_list,num_nodes,result,num_nodes);
}
|
code/graph_algorithms/src/travelling_sales_man_dp/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/graph_algorithms/src/travelling_sales_man_dp/travelling_salesman_dp.cpp | #include <bits/stdc++.h>
using namespace std;
class brute_force
{
public:
int shortest_path_sum(int** edges_list, int num_nodes)
{
int source = 0;
vector<int> nodes;
for(int i=0;i<num_nodes;i++)
{
if(i != source)
{
nodes.push_back(i);
}
}
int n = nodes.size();
int shortest_path = INT_MAX;
while(next_permutation(nodes.begin(),nodes.end()))
{
int path_weight = 0;
int j = source;
for (int i = 0; i < n; i++)
{
path_weight += edges_list[j][nodes[i]];
j = nodes[i];
}
path_weight += edges_list[j][source];
shortest_path = min(shortest_path, path_weight);
}
return shortest_path;
}
};
class dynamic_programming
{
public:
int shortest_path_sum(int** edges_list,int** dp_array,int visited,int mask,int position,int num_nodes)
{
if(mask == visited)
{
return edges_list[position][0];
}
if(dp_array[mask][position] != -1)
{
return dp_array[mask][position];
}
int ans = INT_MAX;
for(int city=0;city<num_nodes;city++){
if((mask&(1<<city))==0){
int newAns = edges_list[position][city] + shortest_path_sum(edges_list,dp_array,visited,mask|(1<<city), city,num_nodes);
ans = min(ans, newAns);
}
}
dp_array[mask][position] = ans;
return dp_array[mask][position] = ans;
}
};
int main()
{
/// Getting the number of nodes and number of edges as input
int num_nodes,num_edges;
cin >> num_nodes >> num_edges;
/// creating a multi-dimensional array
int** edges_list = new int*[num_nodes];
for(int i=0;i<num_nodes;i++)
{
edges_list[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
edges_list[i][j] = 0;
}
}
/// adjacent matrix filling mechanism
for(int i=0;i<num_edges;i++)
{
int first_node,second_node,weight;
cin >> first_node >> second_node >> weight;
edges_list[first_node][second_node] = weight;
edges_list[second_node][first_node] = weight;
}
int visited = (1<<num_nodes)-1;
int m = 1<<num_nodes;
int** dp_array = new int*[m];
for(int i=0;i<m;i++)
{
dp_array[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
dp_array[i][j] = -1;
}
}
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout << edges_list[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
brute_force approach1;
dynamic_programming approach2;
cout << approach1.shortest_path_sum(edges_list,num_nodes) << endl;
cout << approach2.shortest_path_sum(edges_list,dp_array,visited,1,0,num_nodes) << endl;
return 0;
}
|
code/graph_algorithms/src/travelling_salesman_branch&bound/tsp_branch_bound.cpp | #include <bits/stdc++.h>
using namespace std;
// number of total nodes
#define N 5
#define INF INT_MAX
class Node
{
public:
vector<pair<int, int>> path;
int matrix_reduced[N][N];
int cost;
int vertex;
int level;
};
Node* newNode(int matrix_parent[N][N], vector<pair<int, int>> const &path,int level, int i, int j)
{
Node* node = new Node;
node->path = path;
if (level != 0)
node->path.push_back(make_pair(i, j));
memcpy(node->matrix_reduced, matrix_parent,
sizeof node->matrix_reduced);
for (int k = 0; level != 0 && k < N; k++)
{
node->matrix_reduced[i][k] = INF;
node->matrix_reduced[k][j] = INF;
}
node->matrix_reduced[j][0] = INF;
node->level = level;
node->vertex = j;
return node;
}
void reduce_row(int matrix_reduced[N][N], int row[N])
{
fill_n(row, N, INF);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (matrix_reduced[i][j] < row[i])
row[i] = matrix_reduced[i][j];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (matrix_reduced[i][j] != INF && row[i] != INF)
matrix_reduced[i][j] -= row[i];
}
void reduce_column(int matrix_reduced[N][N], int col[N])
{
fill_n(col, N, INF);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (matrix_reduced[i][j] < col[j])
col[j] = matrix_reduced[i][j];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (matrix_reduced[i][j] != INF && col[j] != INF)
matrix_reduced[i][j] -= col[j];
}
int cost_calculation(int matrix_reduced[N][N])
{
int cost = 0;
int row[N];
reduce_row(matrix_reduced, row);
int col[N];
reduce_column(matrix_reduced, col);
for (int i = 0; i < N; i++)
cost += (row[i] != INT_MAX) ? row[i] : 0,
cost += (col[i] != INT_MAX) ? col[i] : 0;
return cost;
}
void printPath(vector<pair<int, int>> const &list)
{
for (int i = 0; i < list.size(); i++)
cout << list[i].first + 1 << " -> "
<< list[i].second + 1 << endl;
}
class comp {
public:
bool operator()(const Node* lhs, const Node* rhs) const
{
return lhs->cost > rhs->cost;
}
};
int solve(int adjacensyMatrix[N][N])
{
priority_queue<Node*, std::vector<Node*>, comp> pq;
vector<pair<int, int>> v;
Node* root = newNode(adjacensyMatrix, v, 0, -1, 0);
root->cost = cost_calculation(root->matrix_reduced);
pq.push(root);
while (!pq.empty())
{
Node* min = pq.top();
pq.pop();
int i = min->vertex;
if (min->level == N - 1)
{
min->path.push_back(make_pair(i, 0));
printPath(min->path);
return min->cost;
}
for (int j = 0; j < N; j++)
{
if (min->matrix_reduced[i][j] != INF)
{
Node* child = newNode(min->matrix_reduced, min->path,
min->level + 1, i, j);
child->cost = min->cost + min->matrix_reduced[i][j]
+ cost_calculation(child->matrix_reduced);
pq.push(child);
}
}
delete min;
}
}
int main()
{
int adjacensyMatrix[N][N] =
{
{ INF, 20, 30, 10, 11 },
{ 15, INF, 16, 4, 2 },
{ 3, 5, INF, 2, 4 },
{ 19, 6, 18, INF, 3 },
{ 16, 4, 7, 16, INF }
};
cout << "\nCost is " << solve(adjacensyMatrix);
return 0;
}
|
code/graph_algorithms/src/travelling_salesman_mst/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.c | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#define MAX_N 21
#define MAX_E (MAX_N * (MAX_N - 1)) / 2
#define MAX_MASK (1 << MAX_N)
#define MAX_W 100
#define NB_ITER 20
int N, fullmask, dp[MAX_N][MAX_MASK];
int G[MAX_N][MAX_N];
/* Result of PVC is stored here. Each element correspond to a
vertice and points to the next vertice in the cycle. */
int cycle[MAX_N];
/* Used to optimize bits operations */
const int BITS_MAP[] = {
32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11,
0, 13, 4, 7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6,
0, 21, 14, 9, 5, 20, 8, 19, 18};
/*
* u is the current vertex.
* mask is the current mask.
*
* Return the cost of the minimum path that goes from u
* to 0 without revisiting already visited vertices.
* Visited vertices are marked with 1 in mask.
*/
int DFS(int u, int mask)
{
if (mask == fullmask)
return dp[u][mask] = G[u][0];
if (dp[u][mask] != -1)
return dp[u][mask];
int v, _v, tmp, cpm = ~mask & fullmask;
dp[u][mask] = INT_MAX;
while (cpm != 0) {
_v = cpm & -cpm;
cpm -= _v;
v = BITS_MAP[_v % 37];
tmp = DFS(v, mask | _v);
if (tmp + G[u][v] < dp[u][mask])
dp[u][mask] = tmp + G[u][v];
}
return dp[u][mask];
}
/*
* Return the weight of the optimal cycle, and
* fill the array cycle (see above).
*/
int PVC()
{
int i, j, ret;
/* Init DP table */
fullmask = (1 << N) - 1;
for (i = 0; i < N; ++i)
for (j = 0; j <= fullmask; ++j)
dp[i][j] = -1;
/* Fill DP table */
ret = DFS(0, 1);
/* Look for the solution */
int u = 0, v = 0, mask = 1, nmask, w, x;
while (mask != fullmask) {
w = INT_MAX;
for (x = 0; x < N; ++x) {
if ((mask & (1 << x)) != 0)
continue;
nmask = mask | (1 << x);
if (dp[x][nmask] + G[u][x] < w) {
v = x;
w = dp[x][nmask] + G[u][x];
}
}
mask |= (1 << v);
cycle[u] = v;
u = v;
}
cycle[u] = 0;
return ret;
}
int main()
{
srand(time(NULL));
int i, j, cpt;
double time_spent;
clock_t begin, end;
/* Execute some benchmarks on different randomly initialized graphs */
for (N = 3; N <= MAX_N; ++N) {
time_spent = 0.f;
for (cpt = 0; cpt < NB_ITER; ++cpt) {
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
G[i][j] = rand() % MAX_W + 1;
G[j][i] = G[i][j];
}
G[i][i] = INT_MAX;
}
begin = clock();
PVC();
end = clock();
time_spent += ((double)(end - begin) / CLOCKS_PER_SEC) * 1000;
}
printf("%d %lf\n", N, time_spent / NB_ITER);
}
return 0;
}
|
code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.cpp | #include <iostream>
#include <vector>
const int MAX = 2000000000;
const int MAX_NODES = 20;
int optimalWayLength[1 << MAX_NODES][MAX_NODES];
bool was[1 << MAX_NODES][MAX_NODES];
int cameFrom[1 << MAX_NODES][MAX_NODES];
int distances[MAX_NODES][MAX_NODES];
int n;
int findAns (int last, int mask)
{
if (mask == (1 << last))
return 0;
if (was[mask][last])
return optimalWayLength[mask][last];
was[mask][last] = true;
int optimal = MAX;
for (int next = 0; next < n; next++)
{
if (next == last)
continue;
if ((mask & (1 << next)) != 0)
{
int distance = distances[next][last] + findAns (next, mask ^ (1 << last));
if (distance < optimal)
{
optimal = distance;
cameFrom[mask][last] = next;
}
}
}
optimalWayLength[mask][last] = optimal;
return optimalWayLength[mask][last];
}
int main()
{
std::cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cin >> distances[i][j];
int optimal = MAX;
int last = 0;
for (int start = 0; start < n; start++)
{
int distance = findAns (start, (1 << n) - 1);
if (distance < optimal)
{
optimal = distance;
last = start;
}
}
int mask = (1 << n) - 1;
std::vector<int> way;
while (mask != 0)
{
way.push_back(last);
int previous = cameFrom[mask][last];
mask ^= 1 << last;
last = previous;
}
std::cout << optimal << '\n';
for (int i = way.size() - 1; i >= 0; i--)
std::cout << way[i] + 1 << ' ';
}
|
code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.py | # Part of Cosmos by OpenGenus Foundation
def solve_tsp_dynamic(points):
# calc all lengths
all_distances = [[length(x, y) for y in points] for x in points]
# initial value - just distance from 0 to every other point + keep the track of edges
A = {
(frozenset([0, idx + 1]), idx + 1): (dist, [0, idx + 1])
for idx, dist in enumerate(all_distances[0][1:])
}
cnt = len(points)
for m in range(2, cnt):
B = {}
for S in [frozenset(C) | {0} for C in itertools.combinations(range(1, cnt), m)]:
for j in S - {0}:
B[(S, j)] = min(
[
(
A[(S - {j}, k)][0] + all_distances[k][j],
A[(S - {j}, k)][1] + [j],
)
for k in S
if k != 0 and k != j
]
) # this will use 0th index of tuple for ordering, the same as if key=itemgetter(0) used
A = B
res = min([(A[d][0] + all_distances[0][d[1]], A[d][1]) for d in iter(A)])
return res[1]
|
code/graph_algorithms/src/vertex_cover/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/graph_algorithms/test/floyd_warshall_graph/floyd_warshal_test.go | package graph
import (
"math"
"testing"
)
const float64EqualityThreshold = 1e-9
//almostEqual subtracts two float64 variables and returns true if they differ less then float64EqualityThreshold
//reference: https://stackoverflow.com/a/47969546
func almostEqual(a, b float64) bool {
return math.Abs(a-b) <= float64EqualityThreshold
}
//IsAlmostEqualTo verifies if two WeightedGraphs can be considered almost equal
func (a *WeightedGraph) IsAlmostEqualTo(b WeightedGraph) bool {
if len(*a) != len(b) {
return false
}
for i := range *a {
if len((*a)[i]) != len(b[i]) {
return false
}
for j := range (*a)[i] {
if (*a)[i][j] == Inf && b[i][j] == Inf {
continue
}
if !almostEqual((*a)[i][j], b[i][j]) {
return false
}
}
}
return true
}
func TestFloydWarshall(t *testing.T) {
var floydWarshallTestData = []struct {
description string
graph [][]float64
expected [][]float64
}{
{
description: "test empty graph",
graph: nil,
expected: nil,
},
{
description: "test graph with wrong dimensions",
graph: [][]float64{
{1, 2},
{Inf},
},
expected: nil,
},
{
description: "test graph with no edges",
graph: [][]float64{
{Inf, Inf},
{Inf, Inf},
},
expected: [][]float64{
{Inf, Inf},
{Inf, Inf},
},
},
{
description: "test graph with only negative edges",
graph: [][]float64{
{-3, -2},
{-3, -2},
},
expected: [][]float64{
{-17, -25},
{-26, -34},
},
},
{
description: "test graph with 5 vertices and self-loops",
graph: [][]float64{
{1, 2, Inf, Inf, Inf},
{Inf, Inf, 3, -4, Inf},
{Inf, Inf, Inf, Inf, 5},
{1, Inf, Inf, Inf, Inf},
{Inf, Inf, Inf, 2, Inf},
},
expected: [][]float64{
{-1, 1, 4, -3, 8},
{-3, -1, 2, -5, 6},
{7, 9, 12, 5, 5},
{0, 2, 5, -2, 9},
{2, 4, 7, 0, 9},
},
},
}
for _, test := range floydWarshallTestData {
t.Run(test.description, func(t *testing.T) {
result := FloydWarshall(test.graph)
if !result.IsAlmostEqualTo(test.expected) {
t.Logf("FAIL: %s", test.description)
t.Fatalf("Expected result:%f\nFound: %f", test.expected, result)
}
})
}
} |
code/graph_algorithms/test/matrix_transformation/test_matrix_transformation.swift | // Part of Cosmos by OpenGenus Foundation
import Foundation
class TestMatrixTransformation {
let mt = MatrixTransformation()
var matrix: [[Int]] = []
let m0: [[Int]] = []
let m1 = [[1]]
let m2 = [[1, 2],
[3, 4]]
let m4 = [[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]
let m5 = [[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
func test() {
testRotate()
testSquareTranspose()
testSquareShear()
}
func testSquareShear() {
let c2 = [[1, 2],
[0, 1]],
c4 = [[1, 0, 0, 0],
[2, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]],
c5 = [[1, 0, 0, 0, 0],
[2, 1, 2, 1, 0],
[1, 0, 1, 2, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]]
let s2 = [[1, 4],
[3,10]],
s4 = [[ 5, 2, 3, 4],
[17, 6, 7, 8],
[29, 10, 11, 12],
[41, 14, 15, 16]],
s5 = [[ 8, 2, 7, 12, 5],
[28, 7, 22, 32, 10],
[48, 12, 37, 52, 15],
[68, 17, 52, 72, 20],
[88, 22, 67, 92, 25]]
let ms = [m0, m1, m2, m4, m5],
cs = [m0, m1, c2, c4, c5],
ss = [m0, m1, s2, s4, s5]
for i in 0..<ms.count {
matrix = ms[i]
mt.squareShearing(matrix: &matrix,
coefficient: cs[i],
init_value: 0,
multiply: ({return $0 * $1}),
add: ({return $0 + $1}))
assert(same(matrix, ss[i]))
}
}
func testSquareTranspose() {
let s2 = [[1, 3],
[2, 4]]
let s4 = [[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15],
[ 4, 8, 12, 16]]
let s5 = [[ 1, 6, 11, 16, 21],
[ 2, 7, 12, 17, 22],
[ 3, 8, 13, 18, 23],
[ 4, 9, 14, 19, 24],
[ 5, 10, 15, 20, 25]]
let r2 = [[4, 2],
[3, 1]]
let r4 = [[16, 12, 8, 4],
[15, 11, 7, 3],
[14, 10, 6, 2],
[13, 9, 5, 1]]
let r5 = [[25, 20, 15, 10, 5],
[24, 19, 14, 9, 4],
[23, 18, 13, 8, 3],
[22, 17, 12, 7, 2],
[21, 16, 11, 6, 1]]
let ms = [m0, m1, m2, m4, m5]
// transpose of the matrices
let ss = [m0, m1, s2, s4, s5]
// reverse transpose of the matrices
let rs = [m0, m1, r2, r4, r5]
for i in 0..<ms.count {
matrix = ms[i]
mt.squareTranspose(&matrix)
assert(same(matrix, ss[i]))
}
for i in 0..<ms.count {
matrix = ms[i]
mt.antiSquareTranspose(&matrix)
assert(same(matrix, rs[i]))
}
}
func testRotate() {
let r2 = [[3, 1],
[4, 2]]
let r4 = [[13, 9, 5, 1],
[14, 10, 6, 2],
[15, 11, 7, 3],
[16, 12, 8, 4]]
let r5 = [[21, 16, 11, 6, 1],
[22, 17, 12, 7, 2],
[23, 18, 13, 8, 3],
[24, 19, 14, 9, 4],
[25, 20, 15, 10, 5]]
let ms = [m0, m1, m2, m4, m5]
// rotate of the matrices
let rs = [m0, m1, r2, r4, r5]
for i in 0..<ms.count {
matrix = ms[i]
mt.rotate(&matrix)
assert(same(matrix, rs[i]))
mt.reverseRotate(&matrix)
assert(same(matrix, ms[i]))
}
}
private func same(_ matrix1: [[Int]], _ matrix2: [[Int]]) -> Bool {
if matrix1.count != matrix2.count {
return false
}
for i in 0..<matrix1.count {
if matrix1[i].count != matrix2[i].count {
return false
}
for j in 0..<matrix1[i].count {
if matrix1[i][j] != matrix2[i][j] {
return false
}
}
}
return true
}
}
|
code/graph_algorithms/test/push_relabel/test_push_relabel.cpp | #define CATCH_CONFIG_MAIN
#include "../../../../test/c++/catch.hpp"
#include "../../src/push_relabel/push_relabel.cpp"
#include <iostream>
int g_testCounter = 0;
std::vector<std::vector<int>> g_graph;
std::vector<std::vector<int>> g_flow;
int test(int s, int t, bool empty)
{
int k = (empty ? maxFlowEmpty(g_graph,s,t) : maxFlow(g_graph,g_flow,s,t));
g_graph.clear();
g_flow.clear();
return k;
}
TEST_CASE("push relabel max flow, zero initial flow")
{
g_graph.push_back(std::vector<int>{ 0, 1, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 1 });
g_graph.push_back(std::vector<int>{ 0, 0, 0 });
REQUIRE(test(0,2,true) == 1);
g_graph.push_back(std::vector<int>{ 0, 1, 0, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 1, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 0, 1 });
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0 });
REQUIRE(test(0,3,true) == 1);
g_graph.push_back(std::vector<int>{ 0, 10, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 5 });
g_graph.push_back(std::vector<int>{ 0, 0, 0 });
REQUIRE(test(0,2,true) == 5);
g_graph.push_back(std::vector<int>{ 0, 10, 10, 0, 0, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 10, 4, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 4, 4, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 12});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 8});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 0});
REQUIRE(test(0,5,true) == 18);
}
TEST_CASE("push relabel max flow, with existing flow")
{
g_graph.push_back(std::vector<int>{ 0, 10, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 5 });
g_graph.push_back(std::vector<int>{ 0, 0, 0 });
g_flow.push_back(std::vector<int>{ 0, 3, 0 });
g_flow.push_back(std::vector<int>{ 0, 0, 3 });
g_flow.push_back(std::vector<int>{ 0, 0, 0 });
REQUIRE(test(0,2,false) == 5);
// wikipedia example
g_graph.push_back(std::vector<int>{ 0, 15, 4, 0, 0, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 12, 0, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 10, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 3, 0, 0, 7});
g_graph.push_back(std::vector<int>{ 0, 5, 0, 0, 0, 10});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 4, 0, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 4, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 0, 4, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 4});
g_flow.push_back(std::vector<int>{ 0, 4, 0, 0, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 0});
REQUIRE(test(0,5,false) == 14);
}
|
code/greedy_algorithms/src/README.md | # Greedy algorithms
> Cosmos: Your personal library of every algorithm and data structure code that you will ever encounter
A greedy algorithm is an algorithmic paradigm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.
In the words of _Jessica Su_, we have:
A greedy algorithm finds the best solution to a problem one step at a time. At each step, the algorithm makes the choice that improves the solution the most, even if that choice makes future steps less fruitful. Sometimes this gives you the right answer to the problem.
Examples:
* Let's say you're at a restaurant and have ordered several dishes. When each dish comes out, you can choose to eat some of it, or save your stomach for the next dish.
Suppose the first dish that comes out is mediocre. A smart person would save their stomach, since they'd rather fill up on better food. But a greedy person would eat a lot of it, because that maximizes their happiness in the moment.
* Suppose you're out hiking, and you want to climb to the top of the tallest mountain, but you don't know where it is. The greedy way to find it would be to start walking in the direction that slopes upward the most, and keep doing this until you reach a peak. (It probably won't be the tallest peak, but that's why greedy algorithms don't work here.)
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/greedy_algorithms/src/SplitArrayLargestSum/README.md | # Split Array Largest Sum
Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these m subarrays.
### Example 1:
Input: nums = [7,2,5,10,8], m = 2
Output: 18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
### Example 2:
Input: nums = [1,2,3,4,5], m = 2
Output: 9
Example 3:
Input: nums = [1,4,4], m = 3
Output: 4
### Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 106
1 <= m <= min(50, nums.length)
## Approach & Solution
We can break this problem into two smaller problems:
1. Given an array (A), number of cuts (CUTS), and the Largest sum of sub-arrays (MAX). Can you use at most CUTS cuts to segment array A into CUTS + 1 sub-arrays, such that the sum of each sub-array is smaller or equal to MAX?
2. Given a lower bound (left), an upper bound (right), an unknown bool array (B), and an API uses i as input and tells you whether B[i] is true. If we know there exists an index k, that B[i] is false when i < k, and B[i] is true when i >= k. What is the fastest way to find this k (the lower bound)?
Solution to the first sub-problem :
For the first question, we can follow these steps:
1. For each element in the array, if its value is larger than MAX, we know it's not possible to cut this array into groups that the sum of all groups are smaller than MAX. (Reason is straightforward, if A is [10, 2, 3, 5] and MAX is 6, even you have 3 cuts by which you can cut A as [[10], [2], [3], [5]], the group containing 10 will still be larger than 6).
2. Use greedy algorithm to cut A. Use an accumulator ACC to store the sum of the currently processed group, and process elements in A one by one. For each element num, if we add num with ACC and the new sum is still no larger than MAX, we update ACC to ACC + num, which means we can merge num into the current group. If not, we must use a cut before num to segment this array, then num will be the first element in the new group.
3. If we didn't go through A but already used up all cuts, then it's not possible only using CUTS cuts to segment this array into groups to make sure sum of each sub-array is smaller than MAX. Otherwise, if we can reach the end of A with cuts left (or use exactly CUTS cuts). It's possible to do so.
Then the first question is solved.
Solution to the second sub-problem :
1. The array B will be something like [false, false, ..., false, true, true, ..., true]. We want to find the index of the first true.
2. Use binary search to find this k. Keep a value mid, mid = (left + right) / 2. If B[mid] = false, then move the search range to the upper half of the original search range, a.k.a left = mid + 1, otherwise move search range to the lower half, a.k.a right = mid.
**Why this algorithm is correct...**
1. No matter how we cut the array A, the Largest sum of sub-arrays will fall into a range [left, right]. Left is the value of the largest element in this array. right is the sum of this array. (e.g., Given array [1, 2, 3, 4, 5], if we have 4 cuts and cut it as [[1], [2], [3], [4], [5]], the Largest sum of sub-arrays is 5, it cannot be smaller. And if we have 0 cut, and the only sub-array is [[1, 2, 3, 4, 5]], the Largest sum of sub-arrays is 15, it cannot be larger).
2. However, we cannot decide the number of cuts (CUTS), this is an given constraint. But we know there must be a magic number k, which is the smallest value of the Largest sum of sub-arrays when given CUTS cuts. When the Largest sum of sub-arrays is larger than k, we can always find a way to cut A within CUTS cuts. When the Largest sum of sub-arrays is smaller than k, there is no way to do this.
**Example**
For example, given array A [1, 2, 3, 4, 5]. We can use 2 cuts.
1. No matter how many cuts are allowed, the range of the possible value of the Largest sum of sub-arrays is [5, 15].
2. When given 2 cuts, we can tell the magic number k here is 6, the result of segmentation is [[1, 2, 3], [4], [5]].
3. When Largest sum of sub-arrays is in range [6, 15], we can always find a way to cut this array within two cuts. You can have a try.
4. However, when Largest sum of sub-arrays is in range [5, 5], there is no way to do this.
5. This mapped this problem into the second sub-problem. Bool array B here is [5:false, 6:true, 7:true, 8:true, ..., 15:true]. We want to find the index i of the first true in B, which is the answer of this entire question, and by solving the first sub-problem, we have an API that can tell us given an i (Largest sum of sub-arrays), whether B[i] is true (whether we can find a way to cut A to satisfy the constraint).
|
code/greedy_algorithms/src/SplitArrayLargestSum/SplitArrayLargestSum.cpp | //CODE
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
/*
Parameters:
nums - The input array;
cuts - How many cuts are available (cuts = #groups - 1);
max - The maximum of the (sum of elements in one group);
Return:
Whether we can use at most 'cuts' number of cuts to segment the entire array,
such that the sum of each group will not exceed 'max'.
*/
bool doable (const vector<int>& nums, int cuts, long long max) {
// 'acc' is the temporary accumulator for the currently processed group.
int acc = 0;
for (int num : nums) {
// If the current processed element in this array is larger than 'max', we cannot segment the array.
// (Reason is straightforward, if 'nums' is [10, 2, 3, 5] and 'max' is 6, even you can have 3 cuts
// (by which you can cut array as [[10], [2], [3], [5]]), the group containing 10 will be larger than 6,
// there is no way to do this).
// Ps: This step is unnecessary in this solution. Because 'left' in the splitArray() function can assure
// 'max' will be larger than every single element. I just want to write a generalized doable() function :)
if (num > max) return false;
// If the (sum of the currently processed group) + (current element) is smaller than max, we can add current
// element into this group.
else if (acc + num <= max) acc += num;
// If not, we will make a cut before this element, and this element will be the first element in the new group.
else {
--cuts;
acc = num;
// If we've used up all cuts, this means this 'max' is not doable.
if (cuts < 0) return false;
}
}
// If we can reach here, this means we've used at most 'cuts' cut to segment the array, and the sum of each groups is
// not larger than 'max'. Yeah!
return true;
}
public:
int splitArray(vector<int>& nums, int m) {
// Use long long to avoid overflow.
long long left = 0, right = 0;
// The smallest possible value ('left') is the the value of the largest element in this array.
// The largest possible value ('right') is the sum of all elements in this array.
for (int num : nums) {
left = max(left, (long long)num);
right += num;
}
// Use binary search, find the lower bound of the possible (minimum sum of groups within m - 1 cuts).
while (left < right) {
long long mid = left + (right - left) / 2;
if (doable(nums, m - 1, mid)) right = mid;
else left = mid + 1;
}
return left;
}
};
// Driver Code Starts.
int main()
{
int t;
cout << "Inpur the number of Test cases :";
cin >> t;
while (t--)
{
int n,m;
cout << "Enter the Quantity of Array Elements: ";
cin >> n;
cout << "Input " << n << " Array elements: ";
vector<int> nums(n);
for (auto &it : nums) {
cin >> it;
}
cout << "Enter the value of m: ";
cin >> m;
Solution ob;
cout << "The largest sum among the " << m << " subarray is " << ob.splitArray(nums, m) << endl;
}
return 0;
} |
code/greedy_algorithms/src/activity_selection/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/greedy_algorithms/src/activity_selection/activity_selection.c | #include <stdio.h>
#include <stdlib.h>
struct activity
{
int start, finish;
};
int
comparator(const void* s1, const void* s2)
{
return ((struct activity *)s1)->finish > ((struct activity *)s2)->finish;
}
void
print_max_activities(struct activity arr[], int n)
{
qsort(arr, n, sizeof(arr[0]), comparator);
printf("Following activities are selected:-");
int i = 0, j;
printf("(%d, %d), ", arr[i].start, arr[i].finish);
for (j = 1; j < n; j++)
if (arr[j].start >= arr[i].finish) {
printf("(%d, %d), ", arr[j].start, arr[j].finish);
i = j;
}
printf("\n");
}
int
main()
{
struct activity arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6},
{5, 7}, {8, 9}};
int n = sizeof(arr) / sizeof(arr[0]);
print_max_activities(arr, n);
return (0);
}
|
code/greedy_algorithms/src/activity_selection/activity_selection.cpp | #include <algorithm>
#include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// A job has start time, finish time and profit.
struct Activitiy
{
int start, finish;
};
// A utility function that is used for sorting
// activities according to finish time
bool activityCompare(Activitiy s1, Activitiy s2)
{
return s1.finish < s2.finish;
}
// Returns count of maximum set of activities that can
// be done by a single person, one at a time.
void printMaxActivities(Activitiy arr[], int n)
{
// Sort jobs according to finish time
sort(arr, arr + n, activityCompare);
cout << "Following activities are selected n";
// The first activity always gets selected
int i = 0;
cout << "(" << arr[i].start << ", " << arr[i].finish << "), ";
// Consider rest of the activities
for (int j = 1; j < n; j++)
// If this activity has start time greater than or
// equal to the finish time of previously selected
// activity, then select it
if (arr[j].start >= arr[i].finish)
{
cout << "(" << arr[j].start << ", "
<< arr[j].finish << "), ";
i = j;
}
}
int main()
{
Activitiy arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6},
{5, 7}, {8, 9}};
int n = sizeof(arr) / sizeof(arr[0]);
printMaxActivities(arr, n);
return 0;
}
|
code/greedy_algorithms/src/activity_selection/activity_selection.java | // Part of Cosmos by OpenGenus Foundation
// Activity selection problem
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class ActivitySelection {
static void activitySelection(List<Activity> activities, int n) {
Collections.sort(activities, new ActivityComparator());
System.out.println("Following activities are selected");
int i= 0, j;
System.out.println(activities.get(i));
for (j = 1; j < n; j++){
if (activities.get(j).start >= activities.get(i).finish){
System.out.println(activities.get(j));
i = j;
}
}
}
public static void main(String args[]) {
List<Activity> activities = new ArrayList<Activity>();
activities.add(new Activity(5, 9));
activities.add(new Activity(1, 2));
activities.add(new Activity(3, 4));
activities.add(new Activity(0, 6));
activities.add(new Activity(5, 7));
activities.add(new Activity(8, 9));
activitySelection(activities, 6);
}
}
class Activity {
int start;
int finish;
Activity(int start, int finish) {
this.start = start;
this.finish = finish;
}
@Override
public String toString() {
return String.format("{start=%d, finish=%d}", start, finish);
}
}
class ActivityComparator implements Comparator<Activity> {
@Override
public int compare(Activity a, Activity b) {
return a.finish < b.finish ? -1 : a.finish == b.finish ? 0 : 1;
}
} |
code/greedy_algorithms/src/activity_selection/activity_selection.py | """
Part of Cosmos by OpenGenus Foundation
Activity Selection Problem
"""
class Activity:
def __init__(self, start, finish):
self.start = start
self.finish = finish
def __lt__(self, other):
return self.finish < other.finish
def __repr__(self):
return "( %s, %s )" % (self.start, self.finish)
def activity_selection(activity_arr):
selected_activities = []
if activity_arr:
activity_arr.sort()
selected = activity_arr[0]
selected_activities.append(selected)
for activity in activity_arr:
if activity.start >= selected.finish:
selected = activity
selected_activities.append(selected)
return selected_activities
activity_arr = [
Activity(5, 9),
Activity(1, 2),
Activity(3, 4),
Activity(0, 6),
Activity(5, 7),
Activity(8, 9),
]
print(activity_selection(activity_arr))
|
code/greedy_algorithms/src/dials_algorithm/dials_algorithm.cpp | // C++ Program for Dijkstra's dial implementation
#include<bits/stdc++.h>
using namespace std;
# define INF 0x3f3f3f3f
// This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// In a weighted graph, we need to store vertex
// and weight pair for every edge
list< pair<int, int> > *adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int u, int v, int w);
// prints shortest path from s
void shortestPath(int s, int W);
};
// Allocates memory for adjacency list
Graph::Graph(int V)
{
this->V = V;
adj = new list< pair<int, int> >[V];
}
// adds edge between u and v of weight w
void Graph::addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
// Prints shortest paths from src to all other vertices.
// W is the maximum weight of an edge
void Graph::shortestPath(int src, int W)
{
/* With each distance, iterator to that vertex in
its bucket is stored so that vertex can be deleted
in O(1) at time of updation. So
dist[i].first = distance of ith vertex from src vertex
dits[i].second = iterator to vertex i in bucket number */
vector<pair<int, list<int>::iterator> > dist(V);
// Initialize all distances as infinite (INF)
for (int i = 0; i < V; i++)
dist[i].first = INF;
// Create buckets B[].
// B[i] keep vertex of distance label i
list<int> B[W * V + 1];
B[0].push_back(src);
dist[src].first = 0;
//
int idx = 0;
while (1)
{
// Go sequentially through buckets till one non-empty
// bucket is found
while (B[idx].size() == 0 && idx < W*V)
idx++;
// If all buckets are empty, we are done.
if (idx == W * V)
break;
// Take top vertex from bucket and pop it
int u = B[idx].front();
B[idx].pop_front();
// Process all adjacents of extracted vertex 'u' and
// update their distanced if required.
for (auto i = adj[u].begin(); i != adj[u].end(); ++i)
{
int v = (*i).first;
int weight = (*i).second;
int du = dist[u].first;
int dv = dist[v].first;
// If there is shorted path to v through u.
if (dv > du + weight)
{
// If dv is not INF then it must be in B[dv]
// bucket, so erase its entry using iterator
// in O(1)
if (dv != INF)
B[dv].erase(dist[v].second);
// updating the distance
dist[v].first = du + weight;
dv = dist[v].first;
// pushing vertex v into updated distance's bucket
B[dv].push_front(v);
// storing updated iterator in dist[v].second
dist[v].second = B[dv].begin();
}
}
}
// Print shortest distances stored in dist[]
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; ++i)
printf("%d %d\n", i, dist[i].first);
}
// Driver program to test methods of graph class
int main()
{
// create the graph given in above fugure
int V = 9;
Graph g(V);
// making above shown graph
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);
// maximum weighted edge - 14
g.shortestPath(0, 14);
return 0;
}
|
code/greedy_algorithms/src/dijkstra_shortest_path/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.c | /*
* From a given vertex in a weighted connected graph, find shortest
* paths to other vertices using Dijkstra's algorithm
*/
#include "stdio.h"
#define infinity 999
void dij(int n, int src, int cost[10][10], int dist[])
{
int i, u, count, flag[10], min;
for(i = 1; i <= n; i++)
flag[i] = 0, dist[i] = cost[src][i];
count = 2;
while(count <= n)
{
min = 99;
for(i = 1; i <= n; i++)
if(dist[i] < min && !flag[i])
min = dist[i], u = i;
flag[u] = 1;
count++;
for(i = 1; i <= n; i++)
if((dist[u] + cost[u][i] < dist[i]) && !flag[i])
dist[i] = dist[u] + cost[u][i];
}
}
void main()
{
int n, src, i, j, cost[10][10], dist[10];
printf("Enter the number of nodes:\n");
scanf("%d",&n);
printf("Enter the cost matrix:\n");
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
{
scanf("%d", &cost[i][j]);
if(cost[i][j] == 0)
cost[i][j] = infinity;
}
printf("Enter the source matrix:\n");
scanf("%d", &src);
dij(n, src, cost, dist);
printf("Shortest path:\n");
for(i = 1; i <= n; i++)
if(i != src)
printf("%d->%d,cost=%d\n", src, i, dist[i]);
}
|
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.cpp | // Implemented by jhbecares based on Dijkstra's algorithm in "Competitive Programming 3"
// Example extracted from problem 10986 - Sending email from UVa Online Judge
/*
* Try with the following data:
* Sample Input
* 3
* 2 1 0 1
* 0 1 100
* 3 3 2 0
* 0 1 100
* 0 2 200
* 1 2 50
* 2 0 0 1
*
* Sample Output
* 100
* 150
* unreachable
*/
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
using namespace std;
int n, m, S, T, w;
vector<vii> AdjList;
vi dist;
priority_queue<ii, vector<ii>, greater<ii>> pq;
void dijkstra(int s)
{
dist.assign(n, 1e9);
dist[s] = 0;
pq.push(ii(0, s));
while (!pq.empty())
{
ii front = pq.top(); pq.pop();
int d = front.first, u = front.second;
if (d > dist[u])
continue;
for (int j = 0; j < (int)AdjList[u].size(); j++)
{
ii v = AdjList[u][j];
if (dist[u] + v.second < dist[v.first])
{
dist[v.first] = dist[u] + v.second;
pq.push(ii(dist[v.first], v.first));
}
}
}
if (dist[T] == 1e9)
cout << "unreachable" << endl;
else
cout << dist[T] << endl;
}
int main()
{
int numCases;
cin >> numCases;
while (numCases--)
{
scanf("%d %d %d %d", &n, &m, &S, &T);
AdjList.assign(n, vii());
int n1, n2;
for (int i = 0; i < m; i++)
{
scanf("%d %d %d", &n1, &n2, &w);
AdjList[n1].push_back(ii(n2, w));
AdjList[n2].push_back(ii(n1, w));
}
dijkstra(S);
}
return 0;
}
|
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.java | // Part of Cosmos by OpenGenus Foundation
public class Dijkstra {
// Dijkstra's algorithm to find shortest path from s to all other nodes
public static int [] dijkstra (WeightedGraph G, int s) {
final int [] dist = new int [G.size()]; // shortest known distance from "s"
final int [] pred = new int [G.size()]; // preceeding node in path
final boolean [] visited = new boolean [G.size()]; // all false initially
for (int i=0; i<dist.length; i++) {
dist[i] = Integer.MAX_VALUE;
}
dist[s] = 0;
for (int i=0; i<dist.length; i++) {
final int next = minVertex (dist, visited);
visited[next] = true;
// The shortest path to next is dist[next] and via pred[next].
final int [] n = G.neighbors (next);
for (int j=0; j<n.length; j++) {
final int v = n[j];
final int d = dist[next] + G.getWeight(next,v);
if (dist[v] > d) {
dist[v] = d;
pred[v] = next;
}
}
}
return pred; // (ignore pred[s]==0!)
}
private static int minVertex (int [] dist, boolean [] v) {
int x = Integer.MAX_VALUE;
int y = -1; // graph not connected, or no unvisited vertices
for (int i=0; i<dist.length; i++) {
if (!v[i] && dist[i]<x) {y=i; x=dist[i];}
}
return y;
}
public static void printPath (WeightedGraph G, int [] pred, int s, int e) {
final java.util.ArrayList path = new java.util.ArrayList();
int x = e;
while (x!=s) {
path.add (0, G.getLabel(x));
x = pred[x];
}
path.add (0, G.getLabel(s));
System.out.println (path);
}
} |
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.py | # Part of Cosmos by OpenGenus Foundation
def dijkstra(graph, source):
vertices, edges = graph
dist = dict()
previous = dict()
for vertex in vertices:
dist[vertex] = float("inf")
previous[vertex] = None
dist[source] = 0
Q = set(vertices)
while len(Q) > 0:
u = minimum_distance(dist, Q)
print("Currently considering", u, "with a distance of", dist[u])
Q.remove(u)
if dist[u] == float("inf"):
break
n = get_neighbours(graph, u)
for vertex in n:
alt = dist[u] + dist_between(graph, u, vertex)
if alt < dist[vertex]:
dist[vertex] = alt
previous[vertex] = u
return previous
|
code/greedy_algorithms/src/egyptian_fraction/egyptian_fraction.c | #include <stdio.h>
/*
This is a program to represent a number in terms of it's Egyptian fraction. An Egyptian Fraction is a finitet sum of unit fractions. Any
positive rational number can be represented by sum of unit fractions.
*/
void printEgyptian(int numerator, int denominator)
{
if (denominator == 0 || numerator == 0)//if numerator is zero, then it cannot be represented as unit fraction. Denominator zero
//implies undefined. So we return.
return;
if (denominator % numerator == 0) {
printf("1/%d", denominator / numerator);//For example 2/4 becomes 1/2
return;
}
if (numerator % denominator == 0) {
printf("%d", numerator / denominator);
return;
}
if (numerator > denominator) {
printf("%d + ", numerator / denominator);
printEgyptian(numerator % denominator, denominator);
return;
}
int n = (denominator / numerator) + 1;
printf("1/%d + ", n);//printing the number found
printEgyptian((numerator * n) - denominator, denominator * n);
}
int
main()
{
int numerator, denominator;
printf("Enter numerator ");
scanf("%d", &numerator);
printf("Enter denominator ");
scanf("%d", &denominator);
printf("Egyptian Fraction Representation of %d/%d is \n", numerator, denominator);
printEgyptian(numerator, denominator);
printf("\n");
return (0);
}
|
code/greedy_algorithms/src/egyptian_fraction/egyptian_fraction.cpp | #include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
void printEgyptian(int numerator, int denominator)
{
if (denominator == 0 || numerator == 0)
return;
if (denominator % numerator == 0)
{
cout << "1/" << denominator / numerator;
return;
}
if (numerator % denominator == 0)
{
cout << numerator / denominator;
return;
}
if (numerator > denominator)
{
cout << numerator / denominator << " + ";
printEgyptian(numerator % denominator, denominator);
return;
}
int n = denominator / numerator + 1;
cout << "1/" << n << " + ";
printEgyptian(numerator * n - denominator, denominator * n);
}
int main()
{
int numerator, denominator;
cin >> numerator >> denominator;
cout << "Egyptian Fraction Representation of "
<< numerator << "/" << denominator << " is\n ";
printEgyptian(numerator, denominator);
return 0;
}
|
code/greedy_algorithms/src/egyptian_fraction/egyptian_fraction.php |
<?php
// Part of Cosmos by OpenGenus
// PHP program to print a fraction
// in Egyptian Form using Greedy
// Algorithm
function printEgyptian($nr, $dr)
{
// If either numerator or
// denominator is 0
if ($dr == 0 || $nr == 0)
return;
// If numerator divides denominator,
// then simple division makes the
// fraction in 1/n form
if ($dr % $nr == 0)
{
echo "1/", (int)$dr / $nr;
return;
}
// If denominator divides numerator,
// then the given number is not fraction
if ($nr%$dr == 0)
{
echo (int)($nr / $dr);
return;
}
// If numerator is more than denominator
if ($nr > $dr)
{
echo (int)($nr/$dr), " + ";
printEgyptian($nr % $dr, $dr);
return;
}
// We reach here dr > nr and dr%nr is
// non-zero. Find ceiling of dr/nr and
// print it as first fraction
$n = (int)($dr / $nr ) + 1;
echo "1/" , $n , " + ";
// Recur for remaining part
printEgyptian($nr * $n - $dr, $dr * $n);
}
// Driver Code
$nr = 6;
$dr = 14;
echo "Egyptian Fraction Representation of ",
$nr, "/", $dr, " is\n ";
printEgyptian($nr, $dr);
?>
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.