filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/game_theory/src/game_of_nim_next_best_move/game_of_nim_next_best_move.py | def nim_sum(objectList, heaps):
nim = 0
# Calculate nim sum for all elements in the objectList
for i in objectList:
nim = nim ^ i
print("The nim sum is {}.".format(nim))
# Determine how many objects to remove from which heap
objects_to_remove = max(objectList) - nim
objects_to_remove = abs(objects_to_remove)
# Logic for certain configurations on determining how many objects to remove from which heap
# "objectList.index(max(objectList))+ 1 )" determines the index in objectList at which the biggest
# heap of objects exists.
if (nim > 0) and (len(objectList) > 2) and (nim != max(objectList)) and (nim != 1):
print(
"Pick {} objects from heap {}".format(
objects_to_remove, objectList.index(max(objectList)) + 1
)
)
break
if (nim > 0) and (len(objectList) > 2) and (nim == max(objectList)) and (nim != 1):
print(
"Pick {} objects from heap {}.".format(
nim, objectList.index(max(objectList)) + 1
)
)
break
if nim > 0 and len(objectList) <= 2 and (objects_to_remove != 0):
print(
"Pick {} objects from heap {}".format(
objects_to_remove, objectList.index(max(objectList)) + 1
)
)
break
if nim > 0 and len(objectList) <= 2 and (objects_to_remove == 0):
print(
"Pick {} objects from heap {}".format(
nim, objectList.index(max(objectList)) + 1
)
)
break
elif (nim == 1) and (len(objectList) <= 2):
print(
"Pick {} objects from heap {}".format(
nim, objectList.index(max(objectList)) + 1
)
)
break
if (nim == 1) and (nim == max(objectList)) and (nim != 0) and (len(objectList) > 2):
print(
"Pick {} objects from heap {}".format(
nim, objectList.index(max(objectList)) + 1
)
)
break
if nim == 0:
print(
"Pick all objects from heap {}.".format(
objectList.index(max(objectList)) + 1
)
)
break
def get_next_optimum(heaps):
"""
Heaps should be in dictionary format where
key : heap number, value : number of objects
Example:
{
1:3,
2:4,
3:5
}
Maximum 5 heaps allowed with maximum 8 objects each
"""
objects = list(heaps.values())
heapKeys = list(heaps.keys())
print(" Your game board looks like this ")
print("-" * 30)
for i in range(len(heapKeys)):
print("Heap {} : {}".format(i + 1, "|" * objects[i]))
print("-" * 30)
nim_sum(objects, heapKeys)
|
code/game_theory/src/game_of_nim_win_loss_prediction/game_of_nim_win_loss_prediction.py | # Code inspiration taken from Wikipedia's Python Implementation
import functools
MISERE = "misere"
NORMAL = "normal"
def nim(heaps, game_type):
"""
Computes next move for Nim, for both game types normal and misere.
Assumption : Both players involved would play without making mistakes.
if there is a winning move:
return tuple(heap_index, amount_to_remove)
else:
return "You will lose :("
"""
print(game_type, heaps, end=" ")
is_misere = game_type == MISERE
endgame_reached = False
count_non_0_1 = sum(1 for x in heaps if x > 1)
endgame_reached = count_non_0_1 <= 1
# nim sum will give the correct end-game move for normal play but
# misere requires the last move be forced onto the opponent
if is_misere and endgame_reached:
moves_left = sum(1 for x in heaps if x > 0)
is_odd = moves_left % 2 == 1
sizeof_max = max(heaps)
index_of_max = heaps.index(sizeof_max)
if sizeof_max == 1 and is_odd:
return "You will lose :("
# reduce the game to an odd number of 1's
return index_of_max, sizeof_max - int(is_odd)
nim_sum = functools.reduce(lambda x, y: x ^ y, heaps)
if nim_sum == 0:
return "You will lose :("
# Calc which move to make
for index, heap in enumerate(heaps):
target_size = heap ^ nim_sum
if target_size < heap:
amount_to_remove = heap - target_size
return index, amount_to_remove
if __name__ == "__main__":
import doctest
doctest.testmod()
|
code/game_theory/src/grundy_numbers_kayle/grundy_numbers_kayle.py | def SGsom(a, b):
"""Returns recurrence Calulation for a and b"""
x = 0
y = 2
while a != 0 or b != 0:
if a % y == b % y:
w = 0
else:
w = 1
x += w * (y / 2)
a -= a % y
b -= b % y
y *= 2
return x
def quickSort(array, left, right):
""" A simple Quick Sorting program"""
i = left
j = right
pivot = array[(left + right) / 2]
while i <= j:
while array[i] < pivot:
i += 1
while array[j] > pivot:
j -= 1
if i <= j:
array[i], array[j] = array[j], array[i]
i += 1
j -= 1
if left < j:
quickSort(array, left, j)
if i < right:
quickSort(array, i, right)
def main():
"""Main Program for printing Grundy Numbers"""
m = input("How Many Sprague Grundy Value do you want to know?")
n = m + 1
main_arr = [0 for i in range(n)]
main_arr[1] = 1
temp_arr = [0 for i in range(n)]
for i in range(2, n):
k = 0
l = 1
for j in range(((i - 1) / 2) + 1):
temp_arr[j] = SGsom(main_arr[j], main_arr[i - j - 1])
for j in range(((i - 2) / 2) + 1):
temp_arr[j + (i + 1) / 2] = SGsom(main_arr[j], main_arr[i - j - 2])
temp_arr[i] = i + 1
quickSort(temp_arr, 0, i - 1)
while k != 1:
if temp_arr[0] != 0:
k += 1
main_arr[i] = 0
elif temp_arr[l] - temp_arr[l - 1] <= 1:
l += 1
else:
k += 1
main_arr[i] = temp_arr[l - 1] + 1
for i in range(m + 1):
print(str(i) + "---" + str(main_arr[i]))
main()
|
code/game_theory/src/minimax/minimax.py | """
Minimax game playing algorithm
Alex Day
Part of Cosmos by OpenGenus Foundation
"""
from abc import ABC, abstractmethod
import math
class Board(ABC):
@abstractmethod
def terminal():
"""
Determine if the current state is terminal
Returns
-------
bool: If the board is terminal
"""
return NotImplementedError()
@abstractmethod
def get_child_board(player):
"""
Get all possible next moves for a given player
Parameters
----------
player: int
the player that needs to take an action (place a disc in the game)
Returns
-------
List: List of all possible next board states
"""
return NotImplementedError()
def minimax(player: int, board, depth_limit, evaluate):
"""
Minimax algorithm with limited search depth.
Parameters
----------
player: int
the player that needs to take an action (place a disc in the game)
board: the current game board instance. Should be a class that extends Board
depth_limit: int
the tree depth that the search algorithm needs to go further before stopping
evaluate: fn[Board, int]
Some function that evaluates the board at the current position
Returns
-------
placement: int or None
the column in which a disc should be placed for the specific player
(counted from the most left as 0)
None to give up the game
"""
max_player = player
next_player = board.PLAYER2 if player == board.PLAYER1 else board.PLAYER1
def value(board, depth_limit):
""" Evaluate the board at the current state
Args:
board (Board): Current board state
depth_limit (int): Depth limit
Returns:
float: Value of the board
"""
return evaluate(player, board)
def max_value(board, depth_limit: int) -> float:
""" Calculate the maximum value for play if players acts optimally
Args:
player (int): Player token to maximize value of
board (Board): Current board state
depth_limit (int): Depth limit
Returns:
float: Maximum value possible if players play optimally
"""
# Check if terminal or depth limit has been reached
if depth_limit == 0 or board.terminal():
# If leaf node return the calculated board value
return value(board, depth_limit)
# If not leaf then continue searching for maximum value
best_value = -math.inf
# Generate all possible moves for maximizing player and store the
# max possible value while exploring down to terminal nodes
for move, child_board in board.get_child_boards(player):
best_value = max(best_value, min_value(child_board, depth_limit - 1))
return best_value
def min_value(board, depth_limit: int) -> float:
""" Calculate the minimum value for play of players acts optimally
Args:
player (int): Player token to minimize value of
board (Board): Current board state
depth_limit (int): Depth limit
Returns:
float: Minimum value possible if players play optimally
"""
# Check if terminal or depth limit has been reached
if depth_limit == 0 or board.terminal():
# If leaf node return the calculated board value
return value(board, depth_limit)
# If not leaf then continue searching for minimum value
best_value = math.inf
# Generate all possible moves for minimizing player and store the
# min possible value while exploring down to terminal nodes
for move, child_board in board.get_child_boards(next_player):
best_value = min(best_value, max_value(child_board, depth_limit - 1))
return best_value
# Start off with the best score as low as possible. We want to maximize
# this for our turn
best_score = -math.inf
placement = None
# Generate all possible moves and boards for the current player
for pot_move, pot_board in board.get_child_boards(player):
# Calculate the minimum score for the player at this board
pot_score = min_value(pot_board, depth_limit - 1)
# If this is greater than the best_score then update
if pot_score > best_score:
best_score = pot_score
placement = pot_move
return placement
|
code/git/undo-changes.md | please refer: https://iq.opengenus.org/p/5a525c5f-e1ac-418c-abac-ff118587dd83/
|
code/git/viewhist.md | please refer
https://iq.opengenus.org/p/911697a3-030c-481a-9793-39138000febd/
|
code/graph_algorithms/src/Number-of-Islands-using-DFS.cpp | // C++Program to count islands in boolean 2D matrix
#include <bits/stdc++.h>
using namespace std;
// A utility function to do DFS for a 2D
// boolean matrix. It only considers
// the 8 neighbours as adjacent vertices
void DFS(vector<vector<int>> &M, int i, int j, int ROW,
int COL)
{
//Base condition
//if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return
if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1)
{
return;
}
if (M[i][j] == 1)
{
M[i][j] = 0;
DFS(M, i + 1, j, ROW, COL); //right side traversal
DFS(M, i - 1, j, ROW, COL); //left side traversal
DFS(M, i, j + 1, ROW, COL); //upward side traversal
DFS(M, i, j - 1, ROW, COL); //downward side traversal
DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal
DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal
DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal
DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal
}
}
int countIslands(vector<vector<int>> &M)
{
int ROW = M.size();
int COL = M[0].size();
int count = 0;
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
if (M[i][j] == 1)
{
count++;
DFS(M, i, j, ROW, COL); //traversal starts from current cell
}
}
}
return count;
}
// Driver Code
int main()
{
vector<vector<int>> M = {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}};
cout << "Number of islands is: " << countIslands(M);
return 0;
}
|
code/graph_algorithms/src/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/adjacency_lists_graph_representation/adjacency_lists_in_c/README.MD | # Adjacency lists graph representation
See main.c for a small example.
|
code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_stack.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
*/
#include "lgraph_stack.h"
/*
* Creates a stack of size n.
* @n The size of the stack.
* @stack A pointer to a stack struct.
* @return 0 on success, -1 on malloc failure.
*/
int
createLG_Stack(size_t n, LG_Stack* stack)
{
stack->n = n;
stack->nodes = malloc(sizeof(*stack->nodes) * n);
if (stack->nodes == NULL)
return (-1);
stack->head = -1;
return (0);
}
/*
* Frees the stack.
* @stack A pointer to a stack struct.
*/
void
freeLG_Stack(LG_Stack* stack)
{
stack->n = 0;
stack->head = -1;
free(stack->nodes);
}
/*
* @stack A pointer to a stack struct.
* @return 1 if the stack is full, 0 otherwise.
*/
inline int
LG_StackFull(LG_Stack* stack)
{
return (stack->head == stack->n);
}
/*
* @stack A pointer to a stack struct.
* @return 1 if the stack is empty, 0 otherwise.
*/
inline int
LG_StackEmpty(LG_Stack* stack)
{
return (stack->head == -1);
}
/*
* Pushes node on top of the stack.
* Doesn't push if the stack is full.
* @stack A pointer to a stack struct.
* @node id of the node to push.
*/
void
LG_StackPush(LG_Stack* stack, Node_ID node)
{
if (LG_StackFull(stack))
return ;
stack->head++;
stack->nodes[stack->head] = node;
}
/*
* Pops the top of the stack.
* Doesn't pop if the stack is empty.
* @stack A pointer to a stack struct.
* @return The id of the node of the top of the stack.
* If the stack is empty, returns 0, but this shouldn't be an indicator,
* since a node of id 0 can be of the top of the stack. Use LG_StackEmpty for checking.
*/
Node_ID
LG_StackPop(LG_Stack* stack)
{
if (LG_StackEmpty(stack))
return (0);
Node_ID ret = stack->nodes[stack->head];
stack->head--;
return (ret);
}
/*
* Peeks the top of the stack whitout poping it.
* @stack A pointer to a stack struct.
* @return Same as LG_StackPop.
*/
Node_ID
LG_StackPeek(LG_Stack* stack)
{
if (LG_StackEmpty(stack))
return (0);
return (stack->nodes[stack->head]);
}
|
code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_stack.h | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Stack for pushing nodes ids.
*/
#ifndef LGRAPH_STACK_H
#define LGRAPH_STACK_H
#include "lgraph_struct.h"
/*
* A common stack definition.
*/
typedef struct
{
size_t n;
Node_ID* nodes;
int head;
} LG_Stack;
/*
* Creates a stack of size n.
* @n The size of the stack.
* @stack A pointer to a stack struct.
* @return 0 on success, -1 on malloc failure.
*/
int
createLG_Stack(size_t n, LG_Stack* stack);
/*
* Frees the stack.
* @stack A pointer to a stack struct.
*/
void
freeLG_Stack(LG_Stack* stack);
/*
* @stack A pointer to a stack struct.
* @return 1 if the stack is full, 0 otherwise.
*/
int
LG_StackFull(LG_Stack* stack);
/*
* @stack A pointer to a stack struct.
* @return 1 if the stack is empty, 0 otherwise.
*/
int
LG_StackEmpty(LG_Stack* stack);
/*
* Pushes node on top of the stack.
* Doesn't push if the stack is full.
* @stack A pointer to a stack struct.
* @node id of the node to push.
*/
void
LG_StackPush(LG_Stack* stack, Node_ID node);
/*
* Pops the top of the stack.
* Doesn't pop if the stack is empty.
* @stack A pointer to a stack struct.
* @return The id of the node of the top of the stack.
* If the stack is empty, returns 0, but this shouldn't be an indicator,
* since a node of id 0 can be of the top of the stack. Use LG_StackEmpty for checking.
*/
Node_ID
LG_StackPop(LG_Stack* stack);
/*
* Peeks the top of the stack whitout poping it.
* @stack A pointer to a stack struct.
* @return Same as LG_StackPop.
*/
Node_ID
LG_StackPeek(LG_Stack* stack);
#endif // LGRAPH_STACK
|
code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_struct.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
*/
#include "lgraph_struct.h"
/* ---------------------------GETTERS-----------------------------------------*/
inline size_t gLG_NbNodes(L_Graph* graph) { return (graph->n); }
inline LG_Node* gLG_NodesArray(L_Graph* graph) { return (graph->nodes); }
inline LG_Node* gLG_Node(L_Graph* graph, Node_ID ID) { return (&graph->nodes[ID]); }
inline Node_ID gNode_ID(LG_Node* node) { return (node->ID); }
inline N_Edges* gNode_EdgesList(LG_Node* node) { return (&node->edges); }
inline int gNode_degree(LG_Node* node) { return (node->edges.degree); }
inline OneEdge* gNode_EdgesHead(LG_Node* node) { return (node->edges.l_edgesHead); }
inline int gEdge_DestNode(OneEdge* edge) { return (edge->nodeID); }
inline OneEdge* gEdgesList_Next(OneEdge* edge) { return (edge->next); }
inline void Node_incDegree(LG_Node* node) { node->edges.degree++; }
/* ----------------------------SETTERS----------------------------------------*/
inline void sLG_NbNodes(L_Graph* graph, size_t n) { graph->n = n; }
inline void sLG_NodesArray(L_Graph* graph, LG_Node* nodes) { graph->nodes = nodes; }
inline void sNode_ID(LG_Node* node, Node_ID ID) { node->ID = ID; }
inline void sNode_degree(LG_Node* node, int degree) { node->edges.degree = degree; }
inline void sNode_EdgesHead(LG_Node* node, OneEdge* head) { node->edges.l_edgesHead = head; }
inline void sEdge_DestNode(OneEdge* edge, int nodeID) { edge->nodeID = nodeID; }
inline void sEdgesList_Next(OneEdge* edge, OneEdge* next) { edge->next = next; }
/* -------------------------ALLOCATION FUNCTIONS------------------------------*/
/*
* Creates a new graph with adjacency-list representation.
*
* @n Number of nodes.
* @graph The struct that will hold the graph.
*
* @return 0 on success.
* -1 when malloc error.
*/
int
createLGraph(size_t n, L_Graph* graph)
{
LG_Node* nodes = malloc(sizeof(*graph->nodes) * n);
if (nodes == NULL)
return (-1);
sLG_NbNodes(graph, n);
sLG_NodesArray(graph, nodes);
Node_ID i;
for (i = 0; i < n; ++i) {
sNode_ID(&nodes[i], i);
initEdgesList(&nodes[i], -1);
}
return (0);
}
/*
* Frees the given graph.
*
* @graph The graph to free.
*/
void
freeLGraph(L_Graph* graph)
{
Node_ID i;
LG_Node* nodes = gLG_NodesArray(graph);
for (i = 0; i < gLG_NbNodes(graph); ++i)
freeEdgesList(&nodes[i]);
free(nodes);
sLG_NbNodes(graph, 0);
}
/*
* Allocate a new edge.
*
* @node_ID The dest node.
* @return A pointer to the new edge on success.
* NULL on failure.
*/
OneEdge*
createEdge(Node_ID node_ID)
{
OneEdge* ret = malloc(sizeof(*ret));
if (ret == NULL)
return NULL;
sEdge_DestNode(ret, node_ID);
sEdgesList_Next(ret, NULL);
return (ret);
}
/*
* Inits edges list of a node.
*
* @edgesList A pointer to the node.
* @head_ID The ID of the node that's going to be the head of the list.
* Give a negative value to avoid head.
* @return 0 on success, -1 on failure.
*/
int
initEdgesList(LG_Node* node, int head_ID)
{
if (head_ID < 0) {
sNode_degree(node, 0);
sNode_EdgesHead(node, NULL);
}
else {
sNode_degree(node, 1);
OneEdge* head = createEdge(head_ID);
if(head == NULL)
return (-1);
sNode_EdgesHead(node, head);
}
return (0);
}
/*
* Frees the edges list of the given node.
*
* @node A pointer to the node.
*/
void
freeEdgesList(LG_Node* node)
{
OneEdge *p = gNode_EdgesHead(node),
*next;
while (p != NULL) {
next = gEdgesList_Next(p);
free(p);
p = next;
}
}
/* --------------------------ADDING EDGES-------------------------------------*/
/*
* Add a new directed edge to the graph, connecting src to dest.
*
* @graph The graph.
* @src_ID ID of the source node.
* @dest_ID ID of the dest node.
*
* @return 0 on success, -1 on failure.
*/
int
LGraph_addDEdge(L_Graph* graph, Node_ID src_ID, Node_ID dest_ID)
{
if (src_ID >= gLG_NbNodes(graph) || dest_ID >= gLG_NbNodes(graph))
return (-1);
return Node_addDEdge(gLG_Node(graph, src_ID), dest_ID);
}
/*
* Connect srcNode to dest_ID by a directed edge.
*
* @srcNode The source node.
* @dest_ID ID of the dest node.
*
* @return 0 on success, -1 on failure.
*/
int
Node_addDEdge(LG_Node* srcNode, Node_ID dest_ID)
{
OneEdge* head = gNode_EdgesHead(srcNode);
if (head == NULL)
return (initEdgesList(srcNode, dest_ID));
OneEdge* newHead = createEdge(dest_ID);
if (newHead == NULL)
return (-1);
sEdgesList_Next(newHead, head);
sNode_EdgesHead(srcNode, newHead);
Node_incDegree(srcNode);
return (0);
}
/*
* Add a new undirected edge to the graph, connecting id1 & id2.
*
* @graph The graph.
* @id1 ID of a node.
* @id2 ID of a node.
*
* @return 0 on success, -1 on failure.
*/
int
LGraph_addUEdge(L_Graph* graph, Node_ID id1, Node_ID id2)
{
if (LGraph_addDEdge(graph, id1, id2) == -1)
return (-1);
/* Loop */
if (id1 == id2)
return (0);
if (LGraph_addDEdge(graph, id2, id1) == -1)
return (-1);
return (0);
}
/*
* Add an undirected edge between node1 & node2.
*
* @node1 a node.
* @node2 a node.
* @return 0 on success, -1 on failure.
*/
int
Node_addUEdge(LG_Node* node1, LG_Node* node2)
{
if (Node_addDEdge(node1, gNode_ID(node2)) == -1)
return (-1);
/* Loop */
if (node1 == node2)
return (0);
if (Node_addDEdge(node2, gNode_ID(node1)) == -1)
return (-1);
return (0);
}
|
code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_struct.h | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Here we have the definition of a graph using adjacency-list representation.
* NB : LG stands for "list graph".
*/
#ifndef GRAPH_STRUCT_H
#define GRAPH_STRUCT_H
#include <stdlib.h>
typedef size_t Node_ID;
/*
* One directed edge.
*/
typedef struct OneEdge
{
Node_ID nodeID; // ID of enter node.
struct OneEdge* next;
} OneEdge;
/*
* Directed edges of a node.
*/
typedef struct
{
int degree; // Number of edges.
OneEdge* l_edgesHead;
} N_Edges;
/*
* Node of a graph with adjacency-list representation.
*/
typedef struct
{
Node_ID ID; // ID of the node.
N_Edges edges;
} LG_Node;
/*
* A Graph struct using adjacency-list representation.
* Let G = (S, A).
*/
typedef struct
{
size_t n; // |S|
LG_Node* nodes; // This will be allocated dynamicaly
} L_Graph;
/* ---------------------------GETTERS-----------------------------------------*/
size_t gLG_NbNodes(L_Graph* graph);
LG_Node* gLG_NodesArray(L_Graph* graph);
LG_Node* gLG_Node(L_Graph* graph, size_t ID);
Node_ID gNode_ID(LG_Node* node);
N_Edges* gNode_EdgesList(LG_Node* node);
int gNode_degree(LG_Node* node);
OneEdge* gNode_EdgesHead(LG_Node* node);
int gEdge_DestNode(OneEdge* edge);
OneEdge* gEdgesList_Next(OneEdge* edge);
void Node_incDegree(LG_Node* node);
/* ----------------------------SETTERS----------------------------------------*/
void sLG_NbNodes(L_Graph* graph, size_t n);
void sLG_NodesArray(L_Graph* graph, LG_Node* nodes);
void sNode_ID(LG_Node* node, Node_ID ID);
void sNode_degree(LG_Node* node, int degree);
void sNode_EdgesHead(LG_Node* node, OneEdge* head);
void sEdge_DestNode(OneEdge* edge, int nodeID);
void sEdgesList_Next(OneEdge* edge, OneEdge* next);
/* -------------------------ALLOCATION FUNCTIONS------------------------------*/
/*
* Creates a new graph with adjacency-list representation.
*
* @n Number of nodes.
* @graph The struct that will hold the graph.
*
* @return 0 on success.
* -1 when malloc error.
*/
int
createLGraph(size_t n, L_Graph* graph);
/*
* Frees the given graph.
*
* @graph The graph to free.
*/
void
freeLGraph(L_Graph* graph);
/*
* Allocate a new edge.
*
* @node_ID The dest node.
* @return A pointer to the new edge on success.
* NULL on failure.
*/
OneEdge*
createEdge(Node_ID node_ID);
/*
* Inits edges list of a node.
*
* @edgesList A pointer to the node.
* @head_ID The ID of the node that's going to be the head of the list.
* Give a negative value to avoid head.
* @return 0 on success, -1 on failure.
*/
int
initEdgesList(LG_Node* node, int head_ID);
/*
* Frees the edges list of the given node.
*
* @node A pointer to the node.
*/
void
freeEdgesList(LG_Node* node);
/* --------------------------ADDING EDGES-------------------------------------*/
/*
* Add a new directed edge to the graph, connecting src to dest.
*
* @graph The graph.
* @src_ID ID of the source node.
* @dest_ID ID of the dest node.
*
* @return 0 on success, -1 on failure.
*/
int
LGraph_addDEdge(L_Graph* graph, Node_ID src_ID, Node_ID dest_ID);
/*
* Connect srcNode to dest_ID by a directed edge.
*
* @srcNode The source node.
* @dest_ID ID of the dest node.
*
* @return 0 on success, -1 on failure.
*/
int
Node_addDEdge(LG_Node* srcNode, Node_ID dest_ID);
/*
* Add a new undirected edge to the graph, connecting id1 & id2.
*
* @graph The graph.
* @id1 ID of a node.
* @id2 ID of a node.
*
* @return 0 on success, -1 on failure.
*/
int
LGraph_addUEdge(L_Graph* graph, Node_ID id1, Node_ID id2);
/*
* Add an undirected edge between node1 & node2.
*
* @node1 a node.
* @node2 a node.
* @return 0 on success, -1 on failure.
*/
int
Node_addUEdge(LG_Node* node1, LG_Node* node2);
#endif // GRAPH_STRUCT
|
code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/main.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
*/
#include <stdio.h>
#include "lgraph_struct.h"
int
main()
{
L_Graph g;
createLGraph(5, &g);
LGraph_addDEdge(&g, 1, 3);
LGraph_addUEdge(&g, 2, 1);
LGraph_addUEdge(&g, 3, 3);
LGraph_addDEdge(&g, 1, 0);
Node_ID i;
LG_Node* n;
OneEdge* p;
for (i = 0; i < gLG_NbNodes(&g); ++i) {
n = gLG_Node(&g, i);
p = gNode_EdgesHead(n);
printf("%d\n", gNode_ID(n));
// Looping over the adjacency-list
while (p != NULL) {
printf("%d\n", gEdge_DestNode(p));
p = gEdgesList_Next(p);
}
printf("\n");
}
freeLGraph(&g);
return (0);
}
|
code/graph_algorithms/src/astar_algorithm/astar_algorithm.js | // Astar algorithm using a Binary Heap instead of a list
/*
Usage:
var astar = require('astar.js');
G = [
[0, ....., 0],
[...........],
[...........],
[0, ....., 0]
];
astar.search(G, start_point, target_point, {});
*/
(function(definition) {
/* global module, define */
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = definition();
} else if (typeof define === "function" && define.amd) {
define([], definition);
} else {
var exports = definition();
window.astar = exports.astar;
window.Graph = exports.Graph;
}
})(function() {
function pathTo(node) {
var curr = node;
var path = [];
while (curr.parent) {
path.unshift(curr);
curr = curr.parent;
}
return path;
}
function getHeap() {
return new BinaryHeap(function(node) {
return node.f;
});
}
var astar = {
/**
* Perform an A* Search on a graph given a start and end node.
* @param {Graph} graph
* @param {GridNode} start
* @param {GridNode} end
* @param {Object} [options]
* @param {bool} [options.closest] Specifies whether to return the
path to the closest node if the target is unreachable.
* @param {Function} [options.heuristic] Heuristic function (see
* astar.heuristics).
*/
search: function(graph, start, end, options) {
graph.cleanDirty();
options = options || {};
var heuristic = options.heuristic || astar.heuristics.manhattan;
var closest = options.closest || false;
var openHeap = getHeap();
var closestNode = start; // set the start node to be the closest if required
start.h = heuristic(start, end);
graph.markDirty(start);
openHeap.push(start);
while (openHeap.size() > 0) {
// Grab the lowest f(x) to process next. Heap keeps this sorted for us.
var currentNode = openHeap.pop();
// End case -- result has been found, return the traced path.
if (currentNode === end) {
return pathTo(currentNode);
}
// Normal case -- move currentNode from open to closed, process each of its neighbors.
currentNode.closed = true;
// Find all neighbors for the current node.
var neighbors = graph.neighbors(currentNode);
for (var i = 0, il = neighbors.length; i < il; ++i) {
var neighbor = neighbors[i];
if (neighbor.closed || neighbor.isWall()) {
// Not a valid node to process, skip to next neighbor.
continue;
}
// The g score is the shortest distance from start to current node.
// We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet.
var gScore = currentNode.g + neighbor.getCost(currentNode);
var beenVisited = neighbor.visited;
if (!beenVisited || gScore < neighbor.g) {
// Found an optimal (so far) path to this node. Take score for node to see how good it is.
neighbor.visited = true;
neighbor.parent = currentNode;
neighbor.h = neighbor.h || heuristic(neighbor, end);
neighbor.g = gScore;
neighbor.f = neighbor.g + neighbor.h;
graph.markDirty(neighbor);
if (closest) {
// If the neighbour is closer than the current closestNode or if it's equally close but has
// a cheaper path than the current closest node then it becomes the closest node
if (
neighbor.h < closestNode.h ||
(neighbor.h === closestNode.h && neighbor.g < closestNode.g)
) {
closestNode = neighbor;
}
}
if (!beenVisited) {
// Pushing to heap will put it in proper place based on the 'f' value.
openHeap.push(neighbor);
} else {
// Already seen the node, but since it has been rescored we need to reorder it in the heap
openHeap.rescoreElement(neighbor);
}
}
}
}
if (closest) {
return pathTo(closestNode);
}
// No result was found - empty array signifies failure to find path.
return [];
},
heuristics: {
manhattan: function(pos0, pos1) {
var d1 = Math.abs(pos1.x - pos0.x);
var d2 = Math.abs(pos1.y - pos0.y);
return d1 + d2;
},
diagonal: function(pos0, pos1) {
var D = 1;
var D2 = Math.sqrt(2);
var d1 = Math.abs(pos1.x - pos0.x);
var d2 = Math.abs(pos1.y - pos0.y);
return D * (d1 + d2) + (D2 - 2 * D) * Math.min(d1, d2);
}
},
cleanNode: function(node) {
node.f = 0;
node.g = 0;
node.h = 0;
node.visited = false;
node.closed = false;
node.parent = null;
}
};
/**
* A graph memory structure
* @param {Array} gridIn 2D array of input weights
* @param {Object} [options]
* @param {bool} [options.diagonal] Specifies whether diagonal moves are allowed
*/
function Graph(gridIn, options) {
options = options || {};
this.nodes = [];
this.diagonal = !!options.diagonal;
this.grid = [];
for (var x = 0; x < gridIn.length; x++) {
this.grid[x] = [];
for (var y = 0, row = gridIn[x]; y < row.length; y++) {
var node = new GridNode(x, y, row[y]);
this.grid[x][y] = node;
this.nodes.push(node);
}
}
this.init();
}
Graph.prototype.init = function() {
this.dirtyNodes = [];
for (var i = 0; i < this.nodes.length; i++) {
astar.cleanNode(this.nodes[i]);
}
};
Graph.prototype.cleanDirty = function() {
for (var i = 0; i < this.dirtyNodes.length; i++) {
astar.cleanNode(this.dirtyNodes[i]);
}
this.dirtyNodes = [];
};
Graph.prototype.markDirty = function(node) {
this.dirtyNodes.push(node);
};
Graph.prototype.neighbors = function(node) {
var ret = [];
var x = node.x;
var y = node.y;
var grid = this.grid;
// West
if (grid[x - 1] && grid[x - 1][y]) {
ret.push(grid[x - 1][y]);
}
// East
if (grid[x + 1] && grid[x + 1][y]) {
ret.push(grid[x + 1][y]);
}
// South
if (grid[x] && grid[x][y - 1]) {
ret.push(grid[x][y - 1]);
}
// North
if (grid[x] && grid[x][y + 1]) {
ret.push(grid[x][y + 1]);
}
if (this.diagonal) {
// Southwest
if (grid[x - 1] && grid[x - 1][y - 1]) {
ret.push(grid[x - 1][y - 1]);
}
// Southeast
if (grid[x + 1] && grid[x + 1][y - 1]) {
ret.push(grid[x + 1][y - 1]);
}
// Northwest
if (grid[x - 1] && grid[x - 1][y + 1]) {
ret.push(grid[x - 1][y + 1]);
}
// Northeast
if (grid[x + 1] && grid[x + 1][y + 1]) {
ret.push(grid[x + 1][y + 1]);
}
}
return ret;
};
Graph.prototype.toString = function() {
var graphString = [];
var nodes = this.grid;
for (var x = 0; x < nodes.length; x++) {
var rowDebug = [];
var row = nodes[x];
for (var y = 0; y < row.length; y++) {
rowDebug.push(row[y].weight);
}
graphString.push(rowDebug.join(" "));
}
return graphString.join("\n");
};
function GridNode(x, y, weight) {
this.x = x;
this.y = y;
this.weight = weight;
}
GridNode.prototype.toString = function() {
return "[" + this.x + " " + this.y + "]";
};
GridNode.prototype.getCost = function(fromNeighbor) {
// Take diagonal weight into consideration.
if (fromNeighbor && fromNeighbor.x != this.x && fromNeighbor.y != this.y) {
return this.weight * 1.41421;
}
return this.weight;
};
GridNode.prototype.isWall = function() {
return this.weight === 0;
};
function BinaryHeap(scoreFunction) {
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to sink down.
this.sinkDown(this.content.length - 1);
},
pop: function() {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it bubble up.
if (this.content.length > 0) {
this.content[0] = end;
this.bubbleUp(0);
}
return result;
},
remove: function(node) {
var i = this.content.indexOf(node);
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if (i !== this.content.length - 1) {
this.content[i] = end;
if (this.scoreFunction(end) < this.scoreFunction(node)) {
this.sinkDown(i);
} else {
this.bubbleUp(i);
}
}
},
size: function() {
return this.content.length;
},
rescoreElement: function(node) {
this.sinkDown(this.content.indexOf(node));
},
sinkDown: function(n) {
// Fetch the element that has to be sunk.
var element = this.content[n];
// When at 0, an element can not sink any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = ((n + 1) >> 1) - 1;
var parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to sink any further.
else {
break;
}
}
},
bubbleUp: function(n) {
// Look up the target element and its score.
var length = this.content.length;
var element = this.content[n];
var elemScore = this.scoreFunction(element);
while (true) {
// Compute the indices of the child elements.
var child2N = (n + 1) << 1;
var child1N = child2N - 1;
// This is used to store the new position of the element, if any.
var swap = null;
var child1Score;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N];
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore) {
swap = child1N;
}
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N];
var child2Score = this.scoreFunction(child2);
if (child2Score < (swap === null ? elemScore : child1Score)) {
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap !== null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};
return {
astar: astar,
Graph: Graph
};
});
|
code/graph_algorithms/src/bellman_ford_algorithm/README.md | # Bellman Ford Algorithm
**Description :** Given a graph and a source vertex *src* in graph, find shortest paths from *src* to all vertices in the given graph. The graph may contain negative edges.
**Time Complexity :** O(VE) *(where V is number of vertices & E is number of edges)*
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/graph_algorithms/src/bellman_ford_algorithm/bellman_ford_algorithm.c | #include <stdio.h>
void relax(int u, int v, double w, double d[], int pi[]) {
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
pi[v] = u;
}
}
void initialize_single_source(double d[], int pi[], int s, int n) {
int i;
for (i = 1; i<= n; ++i) {
d[i] = 1000000000.0;
pi[i] = 0;
}
d[s] = 0.0;
}
int bellman_ford(int first[], int node[], int next[], double w[], double d[],
int pi[], int s, int n) {
int u, v, i, j;
initialize_single_source(d, pi, s, n);
for (i = 1; i<= n-1; ++i) {
for (u = 1; u <= n; ++u) {
j = first[u];
while (j > 0) {
v = node[j];
relax(u, v, w[j], d, pi);
j = next[j];
}
}
}
for (u = 1; u <= n; ++u) {
j = first[u];
while (j > 0) {
v = node[j];
if (d[v] > d[u] + w[j])
return 0;
j = next[j];
}
}
return 1;
}
int main(void) {
int first[6], node[11], next[11], pi[6];
double w[11], d[6];
int s;
int i;
int ok;
first[1] = 1;
first[2] = 3;
first[3] = 6;
first[4] = 7;
first[5] = 9;
node[1] = 2;
node[2] = 4;
node[3] = 3;
node[4] = 4;
node[5] = 5;
node[6] = 2;
node[7] = 3;
node[8] = 5;
node[9] = 1;
node[10] = 3;
w[1] = 6.0;
w[2] = 7.0;
w[3] = 5.0;
w[4] = 8.0;
w[5] = -4.0;
w[6] = -2.0;
w[7] = -3.0;
w[8] = 9.0;
w[9] = 2.0;
w[10] = 7.0;
next[1] = 2;
next[2] = 0;
next[3] = 4;
next[4] = 5;
next[5] = 0;
next[6] = 0;
next[7] = 8;
next[8] = 0;
next[9] = 10;
next[10] = 0;
printf("Enter source node: ");
scanf("%d", &s);
ok = bellman_ford(first, node, next, w, d, pi, s, 5);
printf("bellman_ford returns ");
printf("%d\n\n", ok);
for (i = 1; i<= 5; ++i) {
printf("%d: %f %d\n", i, d[i], pi[i]);
}
return 0;
}
|
code/graph_algorithms/src/bellman_ford_algorithm/bellman_ford_algorithm.cpp | #include <iostream>
#include <map>
#include <vector>
#include <utility>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <climits>
int nodes, edges;
// Path of Cosmos by OpenGenus Foundation
// function to calculate path from source to the given destination
void path_finding(int source, std::unordered_map<int, int> parent_map)
{
using namespace std;
string str;
while (parent_map[source] != source)
{
str.append(to_string(source));
str.append(" ");
source = parent_map[source];
}
str.append(to_string(source));
reverse(str.begin(), str.end());
cout << "Path\n";
cout << str << endl;
}
// A utility function used to print the solution
void print_distance(std::vector<int> distance)
{
using namespace std;
cout << "Distance of vertex corresponding from source\n";
for (size_t i = 0; i < distance.size(); ++i)
cout << i << "\t\t" << distance[i] << endl;
}
// The main function that finds the minimum distance from the source to all other
// vertices using Bellmann ford algorithm
// The function also detects negative weight cycle
void BellmanFord(std::vector<std::pair<int, std::pair<int, int>>> graph, int source,
std::unordered_map<int, int> &parent_map)
{
using namespace std;
vector<int> distance(nodes, INT_MAX);
distance[source] = 0;
// Relax all edges nodes-1 times to get the shortest possible distance
for (int i = 0; i < nodes; i++)
for (int j = 0; j < edges; j++)
{
int source = graph[j].second.first;
int destination = graph[j].second.second;
int weight = graph[j].first;
if (distance[source] != INT_MAX && distance[source] + weight < distance[destination])
{
distance[destination] = distance[source] + weight;
parent_map[destination] = source;
}
}
/* If after relaxing all edges for nodes-1 time we still get a shorter path that indicates
* a negative weight cycle */
for (int j = 0; j < edges; j++)
{
int source = graph[j].second.first;
int destination = graph[j].second.second;
int weight = graph[j].first;
if (distance[source] != INT_MAX && distance[source] + weight < distance[destination])
{
cout << "Graph contains negative weight cycle\n";
exit(0); // If negative cycle found then terminate the program
}
}
print_distance(distance);
}
int main()
{
using namespace std;
vector<pair<int, pair<int, int>>> graph;
unordered_map<int, int> parent_map;
int source, init_path;
cout << "Enter number of nodes in graph\n";
cin >> nodes;
cout << "Enter number of edges is graph\n";
cin >> edges;
for (int i = 0; i < edges; i++)
{
int src, dest, weight;
cout << "Enter source vertex(zero indexed)\n";
cin >> src;
cout << "Enter destination vertex(zero indexed)\n";
cin >> dest;
cout << "Enter weight of edge\n";
cin >> weight;
graph.push_back(make_pair(weight, make_pair(src, dest)));
}
cout << "Enter initial vertex(zero indexed)\n";
cin >> source;
BellmanFord(graph, source, parent_map);
cout << "Enter destination vertex for path finding(zero indexed)\n";
cin >> init_path;
path_finding(init_path, parent_map);
return 0;
}
|
code/graph_algorithms/src/bellman_ford_algorithm/bellman_ford_algorithm.js | /**
* Part of Cosmos by OpenGenus
* Javascript program for Bellman Ford algorithm.
* Given a graph and a source vertex, it finds the
* shortest path to all vertices from source vertex.
*/
class Graph {
constructor(noOfVertices) {
this.V = noOfVertices;
this.graph = [];
}
addEdge(u, v, w) {
this.graph.push([u, v, w]);
}
printSolution(dist) {
console.log("Vertex Distance from Source");
for (let v = 0; v < this.V; v++) {
console.log(`${v} -> ${dist[v]}`);
}
}
bellmanFord(src) {
let dist = Array(this.V).fill(Infinity);
dist[src] = 0;
for (let i = 0; i < this.V - 1; i++) {
for (const [u, v, w] of this.graph) {
if (dist[u] != Infinity && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
}
// Check for negative weight cycle
for (const [u, v, w] of this.graph) {
if (dist[u] != Infinity && dist[u] + w < dist[v]) {
console.log("Negative Weight Cycle is Present");
return;
}
}
this.printSolution(dist);
}
}
g = new Graph(5);
g.addEdge(0, 1, -1);
g.addEdge(0, 2, 4);
g.addEdge(1, 2, 3);
g.addEdge(1, 3, 2);
g.addEdge(1, 4, 2);
g.addEdge(3, 2, 5);
g.addEdge(3, 1, 1);
g.addEdge(4, 3, -3);
g.bellmanFord(0);
|
code/graph_algorithms/src/bellman_ford_algorithm/bellman_ford_algorithm.php | <?php
/*Part of Cosmos by OpenGenus Foundation*/
/*{source, destination, distance}*/
$edges = array(
array(0,1,5),
array(0,2,8),
array(0,3,-4),
array(1,0,-2),
array(2,1,-3),
array(2,3,9),
array(3,1,7),
array(3,4,2),
array(4,0,6),
array(4,2,7),
);
BellmanFord($edges,10,5,4);
function BellmanFord($edges, $edgecount, $nodecount, $source) {
// Initialize distances
$distances = array();
// This is the initialize single source function.
for($i =0; $i < $nodecount; ++$i)
$distances[$i]= INF;
$distances[$source]=0;
// Do what we are suppose to do, This is the BellmanFord function
for($i =0; $i < $nodecount;++$i) {
$somethingChanged =false;
for($j =0; $j < $edgecount;++$j) {
if($distances[$edges[$j][0]]!= INF) {
$newDist = $distances[$edges[$j][0]]+ $edges[$j][2];
if($newDist < $distances[$edges[$j][1]]) {
$distances[$edges[$j][1]]= $newDist;
$somethingChanged =true;
}
}
}
// If $somethingChanged == FALSE, then nothing has changed and we can go on with the next step.
if(!$somethingChanged)break;
}
// Check the graph for negative weight cycles
for($i =0; $i < $edgecount;++$i) {
if($distances[$edges[$i][1]] > $distances[$edges[$i][0]]+ $edges[$i][2]){
echo "Negative edge weight cycle detected!";
return;
}
}
// Print out the shortest distance
for($i =0; $i < $nodecount;++$i) {
echo "Shortest distance between nodes ". $source . " and ". $i ." is ". $distances[$i];
echo "<br>";
}
return;
}
?> |
code/graph_algorithms/src/bellman_ford_algorithm/bellman_ford_algorithm.py | # part of cosmos by OpenGenus Foundation
from collections import defaultdict
# Part of Cosmos by OpenGenus Foundation
class Graph:
def __init__(self, vertices):
self.V = vertices # # of vertices
self.graph = []
# add edge to graph
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
# print solution
def printArr(self, dist):
print("Vertex Distance from Source ")
for i in range(self.V):
print("%d -> %d" % (i, dist[i]))
# main function for bellman ford algo. Also detects negative weight cycles
def bellmanFord(self, src):
# init all distances from source to all as INFINITE
dist = [float("Inf")] * self.V
dist[src] = 0
# relax all edges |V|-1 times.
for i in range(self.V - 1):
# update dist value and parent index of adjacent values of picked vertex.
# consider those which are still in queue.
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
# check for negative weight cycles. If path obtained from above step (shortest distances)
# is shorter, there's a cycle. So quit.
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
print("Negative Cycles !")
return
# print distances
self.printArr(dist)
# dry run
if __name__ == "__main__":
g = Graph(5)
g.addEdge(0, 1, -1)
g.addEdge(0, 2, 4)
g.addEdge(1, 2, 3)
g.addEdge(1, 3, 2)
g.addEdge(1, 4, 2)
g.addEdge(3, 2, 5)
g.addEdge(3, 1, 1)
g.addEdge(4, 3, -3)
g.bellmanFord(0)
|
code/graph_algorithms/src/bellman_ford_algorithm/bellman_ford_algorithm_adjacency_list.java | /**
* An implementation of the Bellman-Ford algorithm. The algorithm finds
* the shortest path between a starting node and all other nodes in the graph.
* The algorithm also detects negative cycles.
*
* @author William Fiset, [email protected]
**/
import java.util.*;
public class BellmanFordAdjacencyList {
// A directed edge with a cost
public static class Edge {
double cost;
int from, to;
public Edge(int from, int to, double cost) {
this.to = to;
this.from = from;
this.cost = cost;
}
}
// Create a graph with V vertices
public static List<Edge>[] createGraph(final int V) {
List <Edge> [] graph = new List[V];
for(int i = 0; i < V; i++) graph[i] = new ArrayList<>();
return graph;
}
// Helper function to add an edge to the graph
public static void addEdge(List<Edge>[] graph, int from, int to, double cost) {
graph[from].add(new Edge(from, to, cost));
}
/**
* An implementation of the Bellman-Ford algorithm. The algorithm finds
* the shortest path between a starting node and all other nodes in the graph.
* The algorithm also detects negative cycles. If a node is part of a negative
* cycle then the minimum cost for that node is set to Double.NEGATIVE_INFINITY.
*
* @param graph - An adjacency list containing directed edges forming the graph
* @param V - The number of vertices in the graph.
* @param start - The id of the starting node
**/
public static double[] bellmanFord(List<Edge>[] graph, int V, int start) {
// Initialize the distance to all nodes to be infinity
// except for the start node which is zero.
double[] dist = new double[V];
java.util.Arrays.fill(dist, Double.POSITIVE_INFINITY);
dist[start] = 0;
// For each vertex, apply relaxation for all the edges
for (int i = 0; i < V-1; i++)
for(List<Edge> edges : graph)
for (Edge edge : edges)
if (dist[edge.from] + edge.cost < dist[edge.to])
dist[edge.to] = dist[edge.from] + edge.cost;
// Run algorithm a second time to detect which nodes are part
// of a negative cycle. A negative cycle has occurred if we
// can find a better path beyond the optimal solution.
for (int i = 0; i < V-1; i++)
for(List<Edge> edges : graph)
for (Edge edge : edges)
if (dist[edge.from] + edge.cost < dist[edge.to])
dist[edge.to] = Double.NEGATIVE_INFINITY;
// Return the array containing the shortest distance to every node
return dist;
}
public static void main(String[] args) {
int E = 10, V = 9, start = 0;
List <Edge> [] graph = createGraph(V);
addEdge(graph, 0, 1, 1);
addEdge(graph, 1, 2, 1);
addEdge(graph, 2, 4, 1);
addEdge(graph, 4, 3, -3);
addEdge(graph, 3, 2, 1);
addEdge(graph, 1, 5, 4);
addEdge(graph, 1, 6, 4);
addEdge(graph, 5, 6, 5);
addEdge(graph, 6, 7, 4);
addEdge(graph, 5, 7, 3);
double[] d = bellmanFord(graph, V, start);
for (int i = 0; i < V; i++)
System.out.printf("The cost to get from node %d to %d is %.2f\n", start, i, d[i] );
// Output:
// The cost to get from node 0 to 0 is 0.00
// The cost to get from node 0 to 1 is 1.00
// The cost to get from node 0 to 2 is -Infinity
// The cost to get from node 0 to 3 is -Infinity
// The cost to get from node 0 to 4 is -Infinity
// The cost to get from node 0 to 5 is 5.00
// The cost to get from node 0 to 6 is 5.00
// The cost to get from node 0 to 7 is 8.00
// The cost to get from node 0 to 8 is Infinity
}
}
|
code/graph_algorithms/src/bellman_ford_algorithm/bellman_ford_algorithm_edge_list.java | /**
* An implementation of the Bellman-Ford algorithm. The algorithm finds
* the shortest path between a starting node and all other nodes in the graph.
* The algorithm also detects negative cycles.
*
* @author William Fiset, [email protected]
**/
public class BellmanFordEdgeList {
// A directed edge
public static class Edge {
double cost;
int from, to;
public Edge(int from, int to, double cost) {
this.to = to;
this.from = from;
this.cost = cost;
}
}
/**
* An implementation of the Bellman-Ford algorithm. The algorithm finds
* the shortest path between a starting node and all other nodes in the graph.
* The algorithm also detects negative cycles. If a node is part of a negative
* cycle then the minimum cost for that node is set to Double.NEGATIVE_INFINITY.
*
* @param edges - An edge list containing directed edges forming the graph
* @param V - The number of vertices in the graph.
* @param start - The id of the starting node
**/
public static double[] bellmanFord(Edge[] edges, int V, int start) {
double[] dist = new double[V];
java.util.Arrays.fill(dist, Double.POSITIVE_INFINITY);
dist[start] = 0;
// For each vertex, apply relaxation for all the edges
for (int v = 0; v < V-1; v++)
for (Edge edge : edges)
if (dist[edge.from] + edge.cost < dist[edge.to])
dist[edge.to] = dist[edge.from] + edge.cost;
// Run algorithm a second time to detect which nodes are part
// of a negative cycle. A negative cycle has occurred if we
// can find a better path beyond the optimal solution.
for (int v = 0; v < V-1; v++)
for (Edge edge : edges)
if (dist[edge.from] + edge.cost < dist[edge.to])
dist[edge.to] = Double.NEGATIVE_INFINITY;
// Return the array containing the shortest distance to every node
return dist;
}
public static void main(String[] args) {
int E = 10, V = 9, start = 0;
Edge [] edges = new Edge[E];
edges[0] = new Edge(0,1,1);
edges[1] = new Edge(1,2,1);
edges[2] = new Edge(2,4,1);
edges[3] = new Edge(4,3,-3);
edges[4] = new Edge(3,2,1);
edges[5] = new Edge(1,5,4);
edges[6] = new Edge(1,6,4);
edges[7] = new Edge(5,6,5);
edges[8] = new Edge(6,7,4);
edges[9] = new Edge(5,7,3);
double[] d = bellmanFord(edges, V, start);
for (int i = 0; i < V; i++)
System.out.printf("The cost to get from node %d to %d is %.2f\n", start, i, d[i] );
// Output:
// The cost to get from node 0 to 0 is 0.00
// The cost to get from node 0 to 1 is 1.00
// The cost to get from node 0 to 2 is -Infinity
// The cost to get from node 0 to 3 is -Infinity
// The cost to get from node 0 to 4 is -Infinity
// The cost to get from node 0 to 5 is 5.00
// The cost to get from node 0 to 6 is 5.00
// The cost to get from node 0 to 7 is 8.00
// The cost to get from node 0 to 8 is Infinity
}
}
|
code/graph_algorithms/src/biconnected_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/biconnected_components/biconnected_components.cpp | #include <iostream>
#include <list>
#include <stack>
#define NIL -1
using namespace std;
int totalCount = 0;
class Edge
{
public:
int u;
int v;
Edge(int u, int v);
};
Edge::Edge(int u, int v)
{
this->u = u;
this->v = v;
}
// A class that represents an directed graph
class Graph
{
int V; // No. of vertices
int E; // No. of edges
list<int> *adj; // A dynamic array of adjacency lists
// A Recursive DFS based function used by BCC()
void BCCUtil(int u, int disc[], int low[],
list<Edge> *st, int parent[]);
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
void BCC(); // prints strongly connected components
};
Graph::Graph(int V)
{
this->V = V;
this->E = 0;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
E++;
}
// A recursive function that finds and prints strongly connected
// components using DFS traversal
// u --> The vertex to be visited next
// disc[] --> Stores discovery times of visited vertices
// low[] -- >> earliest visited vertex (the vertex with minimum
// discovery time) that can be reached from subtree
// rooted with current vertex
// *st -- >> To store visited edges
void Graph::BCCUtil(int u, int disc[], int low[], list<Edge> *st,
int parent[])
{
// A static variable is used for simplicity, we can avoid use
// of static variable by passing a pointer.
static int time = 0;
// Initialize discovery time and low value
disc[u] = low[u] = ++time;
int children = 0;
// Go through all vertices adjacent to this
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
{
int v = *i; // v is current adjacent of 'u'
// If v is not visited yet, then recur for it
if (disc[v] == -1)
{
children++;
parent[v] = u;
//store the edge in stack
st->push_back(Edge(u, v));
BCCUtil(v, disc, low, st, parent);
// Check if the subtree rooted with 'v' has a
// connection to one of the ancestors of 'u'
// Case 1 -- per Strongly Connected Components Article
low[u] = min(low[u], low[v]);
//If u is an articulation point,
//pop all edges from stack till u -- v
if ( (disc[u] == 1 && children > 1) ||
(disc[u] > 1 && low[v] >= disc[u]) )
{
while (st->back().u != u || st->back().v != v)
{
cout << st->back().u << "--" << st->back().v << " ";
st->pop_back();
}
cout << st->back().u << "--" << st->back().v;
st->pop_back();
cout << endl;
totalCount++;
}
}
// Update low value of 'u' only of 'v' is still in stack
// (i.e. it's a back edge, not cross edge).
// Case 2 -- per Strongly Connected Components Article
else if (v != parent[u] && disc[v] < low[u])
{
low[u] = min(low[u], disc[v]);
st->push_back(Edge(u, v));
}
}
}
// The function to do DFS traversal. It uses BCCUtil()
void Graph::BCC()
{
int *disc = new int[V];
int *low = new int[V];
int *parent = new int[V];
list<Edge> *st = new list<Edge>[E];
// Initialize disc and low, and parent arrays
for (int i = 0; i < V; i++)
{
disc[i] = NIL;
low[i] = NIL;
parent[i] = NIL;
}
for (int i = 0; i < V; i++)
{
if (disc[i] == NIL)
BCCUtil(i, disc, low, st, parent);
int j = 0;
//If stack is not empty, pop all edges from stack
while (st->size() > 0)
{
j = 1;
cout << st->back().u << "--" << st->back().v << " ";
st->pop_back();
}
if (j == 1)
{
cout << endl;
totalCount++;
}
}
}
int main()
{
Graph g(12);
g.addEdge(0, 1); g.addEdge(1, 0);
g.addEdge(1, 2); g.addEdge(2, 1);
g.addEdge(1, 3); g.addEdge(3, 1);
g.addEdge(2, 3); g.addEdge(3, 2);
g.addEdge(2, 4); g.addEdge(4, 2);
g.addEdge(3, 4); g.addEdge(4, 3);
g.addEdge(1, 5); g.addEdge(5, 1);
g.addEdge(0, 6); g.addEdge(6, 0);
g.addEdge(5, 6); g.addEdge(6, 5);
g.addEdge(5, 7); g.addEdge(7, 5);
g.addEdge(5, 8); g.addEdge(8, 5);
g.addEdge(7, 8); g.addEdge(8, 7);
g.addEdge(8, 9); g.addEdge(9, 8);
g.addEdge(10, 11); g.addEdge(11, 10);
g.BCC();
cout << "Above are " << totalCount << " biconnected components in graph";
return 0;
}
|
code/graph_algorithms/src/biconnected_components/biconnected_components.java | import java.util.*;
public class Biconnectivity {
List<Integer>[] graph;
boolean[] visited;
Stack<Integer> stack;
int time;
int[] tin;
int[] lowlink;
List<List<Integer>> edgeBiconnectedComponents;
List<Integer> cutPoints;
List<String> bridges;
public List<List<Integer>> biconnectivity(List<Integer>[] graph) {
int n = graph.length;
this.graph = graph;
visited = new boolean[n];
stack = new Stack<>();
time = 0;
tin = new int[n];
lowlink = new int[n];
edgeBiconnectedComponents = new ArrayList<>();
cutPoints = new ArrayList<>();
bridges = new ArrayList<>();
for (int u = 0; u < n; u++)
if (!visited[u])
dfs(u, -1);
return edgeBiconnectedComponents;
}
void dfs(int u, int p) {
visited[u] = true;
lowlink[u] = tin[u] = time++;
stack.add(u);
int children = 0;
boolean cutPoint = false;
for (int v : graph[u]) {
if (v == p)
continue;
if (visited[v]) {
lowlink[u] = Math.min(lowlink[u], tin[v]); // or lowlink[u] = Math.min(lowlink[u], lowlink[v]);
} else {
dfs(v, u);
lowlink[u] = Math.min(lowlink[u], lowlink[v]);
cutPoint |= tin[u] <= lowlink[v];
if (tin[u] < lowlink[v]) // or if (lowlink[v] == tin[v])
bridges.add("(" + u + "," + v + ")");
++children;
}
}
if (p == -1)
cutPoint = children >= 2;
if (cutPoint)
cutPoints.add(u);
if (tin[u] == lowlink[u]) {
List<Integer> component = new ArrayList<>();
while (true) {
int x = stack.pop();
component.add(x);
if (x == u)
break;
}
edgeBiconnectedComponents.add(component);
}
}
public static List<Integer>[] ebcTree(List<Integer>[] graph, List<List<Integer>> components) {
int[] comp = new int[graph.length];
for (int i = 0; i < components.size(); i++)
for (int u : components.get(i))
comp[u] = i;
List<Integer>[] g = Stream.generate(ArrayList::new).limit(components.size()).toArray(List[]::new);
for (int u = 0; u < graph.length; u++)
for (int v : graph[u])
if (comp[u] != comp[v])
g[comp[u]].add(comp[v]);
return g;
}
public static void main(String[] args) {
List<Integer>[] graph = Stream.generate(ArrayList::new).limit(6).toArray(List[]::new);
int[][] esges = {{0, 1}, {1, 2}, {0, 2}, {2, 3}, {1, 4}, {4, 5}, {5, 1}};
for (int[] edge : esges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
Biconnectivity bc = new Biconnectivity();
List<List<Integer>> components = bc.biconnectivity(graph);
System.out.println("edge-biconnected components:" + components);
System.out.println("cut points: " + bc.cutPoints);
System.out.println("bridges:" + bc.bridges);
System.out.println("condensation tree:" + Arrays.toString(ebcTree(graph, components)));
}
}
|
code/graph_algorithms/src/biconnected_components/biconnected_components.py | """
This program reads the structure of the undirected graph for stdin, you can
feed it with a file using input/output redirections.
The structure of the input is :
number_of_nodes number_of_edges
u1 v1
u2 v2
...
"""
def dfs(u, p):
global T
V[u] = 1
disc[u] = T
low[u] = T
T = T + 1
# Used to count the number of children of a node
count = 0
for v in G[u]:
if V[v] == 0:
dfs(v, u)
low[u] = min(low[u], low[v])
count = count + 1
if p != -1 and low[v] >= disc[u]:
L.add(u)
elif V[v] == 1 and v != p:
low[u] = min(low[u], disc[v])
V[u] = 2
# This node is the root of the DFS tree, so it must be a cut vertex
if p == -1 and count > 1:
L.add(u)
# Read graph information from stdin
N, M = [int(s) for s in input().split(" ") if s != ""]
G = [list() for i in range(0, N)]
for i in range(0, M):
u, v = [int(s) for s in input().split(" ") if s != ""]
G[u].append(v)
G[v].append(u)
# List of cut vertices
L = set()
# Array of visited nodes
# 0 : not visited
# 1 : currently visiting
# 2 : visited
V = [0] * N
T = 0
disc = [0] * N
low = [0] * N
# Go for DFS
for i in range(0, N):
if V[i] == 0:
dfs(i, -1)
print(L)
|
code/graph_algorithms/src/bipartite_check/bipartite_check.cpp | // C++ program to find out whether a
// given graph is Bipartite or not
#include <iostream>
#include <queue>
#define V 4
using namespace std;
// This function returns true if graph
// G[V][V] is Bipartite, else false
bool isBipartite(int G[][V], int src)
{
// Create a color array to store colors
// assigned to all veritces. Vertex
// number is used as index in this array.
// The value '-1' of colorArr[i]
// is used to indicate that no color
// is assigned to vertex 'i'. The value 1
// is used to indicate first color
// is assigned and value 0 indicates
// second color is assigned.
int colorArr[V];
for (int i = 0; i < V; ++i)
colorArr[i] = -1;
// Assign first color to source
colorArr[src] = 1;
// Create a queue (FIFO) of vertex
// numbers and enqueue source vertex
// for BFS traversal
queue <int> q;
q.push(src);
// Run while there are vertices
// in queue (Similar to BFS)
while (!q.empty())
{
// Dequeue a vertex from queue ( Refer http://goo.gl/35oz8 )
int u = q.front();
q.pop();
// Return false if there is a self-loop
if (G[u][u] == 1)
return false;
// Find all non-colored adjacent vertices
for (int v = 0; v < V; ++v)
{
// An edge from u to v exists and
// destination v is not colored
if (G[u][v] && colorArr[v] == -1)
{
// Assign alternate color to this adjacent v of u
colorArr[v] = 1 - colorArr[u];
q.push(v);
}
// An edge from u to v exists and destination
// v is colored with same color as u
else if (G[u][v] && colorArr[v] == colorArr[u])
return false;
}
}
// If we reach here, then all adjacent
// vertices can be colored with alternate color
return true;
}
// Driver program to test above function
int main()
{
int G[][V] = {{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}
};
isBipartite(G, 0) ? cout << "Yes" : cout << "No";
return 0;
}
|
code/graph_algorithms/src/bipartite_check/bipartite_check.java | // Java program to find out whether a given graph is Bipartite or not
import java.util.*;
import java.lang.*;
import java.io.*;
// Part of Cosmos by OpenGenus Foundation
class Bipartite
{
final static int V = 4; // No. of Vertices
// This function returns true if graph G[V][V] is Bipartite, else false
boolean isBipartite(int G[][],int src)
{
// Create a color array to store colors assigned to all veritces.
// Vertex number is used as index in this array. The value '-1'
// of colorArr[i] is used to indicate that no color is assigned
// to vertex 'i'. The value 1 is used to indicate first color
// is assigned and value 0 indicates second color is assigned.
int colorArr[] = new int[V];
for (int i=0; i<V; ++i)
colorArr[i] = -1;
// Assign first color to source
colorArr[src] = 1;
// Create a queue (FIFO) of vertex numbers and enqueue
// source vertex for BFS traversal
LinkedList<Integer>q = new LinkedList<Integer>();
q.add(src);
// Run while there are vertices in queue (Similar to BFS)
while (q.size() != 0)
{
// Dequeue a vertex from queue
int u = q.poll();
// Return false if there is a self-loop
if (G[u][u] == 1)
return false;
// Find all non-colored adjacent vertices
for (int v=0; v<V; ++v)
{
// An edge from u to v exists and destination v is
// not colored
if (G[u][v]==1 && colorArr[v]==-1)
{
// Assign alternate color to this adjacent v of u
colorArr[v] = 1-colorArr[u];
q.add(v);
}
// An edge from u to v exists and destination v is
// colored with same color as u
else if (G[u][v]==1 && colorArr[v]==colorArr[u])
return false;
}
}
// If we reach here, then all adjacent vertices can
// be colored with alternate color
return true;
}
// Driver program to test above function
public static void main (String[] args)
{
int G[][] = {{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}
};
Bipartite b = new Bipartite();
if (b.isBipartite(G, 0))
System.out.println("Yes");
else
System.out.println("No");
}
}
|
code/graph_algorithms/src/bipartite_checking/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/bipartite_checking/bipartite_checking.cpp | #include <iostream>
#include <queue>
using namespace std;
int bipartite(int g[][10], int s, int n)
{
int *col = new int [n];
for (int i = 0; i < n; i++)
col[i] = -1;
queue<int> q;
col[s] = 1;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
if (g[u][u] == 1)
return 0;
for (int v = 0; v < n; v++)
{
if (g[u][v] && col[v] == -1)
{
col[v] = 1 - col[u];
q.push(v);
}
else if (g[u][v] == 1 && col[u] == col[v])
return 0;
}
}
return 1;
}
int main()
{
int g[10][10], n;
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> g[i][j];
int x = bipartite(g, 0, n);
cout << x << endl;
return 0;
}
|
code/graph_algorithms/src/bipartite_checking/bipartite_checking.java | import java.util.*;
import java.lang.*;
import java.io.*;
// Program to Check whether Graph is a Bipartite using BFS
public class BipartiteBfs
{
private int numberOfVertices;
private Queue<Integer> queue;
public static final int NO_COLOR = 0;
public static final int RED = 1;
public static final int BLUE = 2;
public BipartiteBfs(int numberOfVertices)
{
this.numberOfVertices = numberOfVertices;
queue = new LinkedList<Integer>();
}
public boolean isBipartite(int adjacencyMatrix[][], int source)
{
int[] colored = new int[numberOfVertices + 1];
for (int vertex = 1; vertex <= numberOfVertices; vertex++)
{
colored[vertex] = NO_COLOR;
}
colored[source] = RED;
queue.add(source);
int element, neighbour;
while (!queue.isEmpty())
{
element = queue.remove();
neighbour = 1;
while (neighbour <= numberOfVertices)
{
if (adjacencyMatrix[element][neighbour] == 1 && colored[element]== colored[neighbour])
{
return false;
}
if (adjacencyMatrix[element][neighbour] == 1 && colored[neighbour]== NO_COLOR)
{
colored[neighbour] = (colored[element] == RED ) ? BLUE :RED;
queue.add(neighbour);
}
neighbour++;
}
}
return true;
}
//The Main function
public static void main(String[] args)
{
int number_of_nodes, source;
Scanner scanner = new Scanner(System.in);
try
{
System.out.println("Enter the number of nodes in the graph");
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
adjacency_matrix[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
if(adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
BipartiteBfs bipartiteBfs = new BipartiteBfs(number_of_nodes);
if (bipartiteBfs.isBipartite(adjacency_matrix, source))
{
System.out.println("The given graph is bipartite");
} else
{
System.out.println("The given graph is not bipartite");
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
}
}
/*
Sample Case ::
Input ::
Enter the number of nodes in the graph
4
Enter the adjacency matrix
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Enter the source for the graph
1
Output ::
The given graph is bipartite
*/ |
code/graph_algorithms/src/bipartite_checking/bipartite_checking2.cpp | #include <iostream>
#include <vector>
#include <algorithm>
/* Part of Cosmos by OpenGenus Foundation */
bool dfs(int v, std::vector<std::vector<int>> &g, std::vector<int> &dp)
{
for (int u : g[v])
{
if (!dp[u])
{
dp[u] = 3 - dp[v]; // 3 - 1 = 2; 3 - 2 = 1
dfs(u, g, dp);
}
if (dp[u] != 3 - dp[v])
return false;
}
return true;
}
// Time complexity: O(|V| + |E|)
bool check_bipartite(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])
{
dp[i] = 1;
if (!dfs(i, g, dp))
return false;
}
return true;
}
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. 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);
g[v].push_back(u);
}
if (check_bipartite(g))
std::cout << "This graph is bipartite.\n";
else
std::cout << "This graph is not bipartite.\n";
return 0;
}
|
code/graph_algorithms/src/bipartite_checking/bipartite_checking_adjacency_list.java | /**
* Part of Cosmos by OpenGenus Foundation.
*
* This file shows you how to determine if a graph is bipartite or not.
* This can be achieved in linear time by coloring the visited nodes.
*
* Time Complexity: O(V + E)
*
* @author William Fiset, [email protected]
**/
import java.util.*;
class Edge {
int from, to;
public Edge(int from, int to) {
this.from = from;
this.to = to;
}
}
public class BipartiteGraphCheckAdjacencyList {
private static final int BLACK = 0, RED = 1, UNVISITED = 2;
// Checks whether a certain graph represented as a adjacency list can
// be setup as a bipartite graph. If it is bipartite, this method returns
// an array of colors indicating to which group each node belongs to or
// null if the graph is not bipartite. Note that because the entire graph
// is not bipartite does not mean that the individual connected components
// of the graph cannot be disjointly bipartite themselves.
public static int[] isBipartite(Map <Integer,List<Edge>> graph, int n) {
// Graph cannot be bipartite if there is only one node
if (n <= 1) return null;
// The graph must be connected and undirected otherwise it is not bipartite
if (graph.size() != n) return null;
int[] colors = new int[n];
java.util.Arrays.fill(colors, UNVISITED);
int nodesVisited = colorGraph(0, BLACK, colors, graph);
// This graph is not bipartite
if (nodesVisited == -1) return null;
// Make sure we were able to visit all the nodes in
// the graph, otherwise it is not bipartite
if (nodesVisited != n) return null;
return colors;
}
// Do a depth first search coloring the nodes of the graph as we go.
// This method returns the count of the number of nodes visited while
// coloring the graph or -1 if this graph is not bipartite.
private static int colorGraph(int i, int color, int[] colors, Map<Integer,List<Edge>> graph) {
// This node is already colored the correct color
if (colors[i] == color) return 0;
// Color this node
colors[i] = color;
// Swap colors. A less explicit way of swapping colors
// is to say: nextColor = 1 - color; to flip the parity
int nextColor = (color == BLACK) ? RED : BLACK;
List <Edge> edges = graph.get(i);
int visitCount = 1;
// Do a depth first search to explore all nodes which have
// not already been colored with the next color. This includes
// all unvisited nodes and also nodes of the current color because
// we want to check for a contradiction if one exists.
for(Edge edge : edges) {
// Contradiction found. In a bipartite graph no two
// nodes of the same color can be next to each other!
if (colors[edge.to] == color) return -1;
// Attempt to color the rest of the graph.
int count = colorGraph(edge.to, nextColor, colors, graph);
// If a contradiction is found propagate return -1
// otherwise keep track of the number of visited nodes
if (count == -1) return -1;
else visitCount += count;
}
return visitCount;
}
// Examples
public static void main(String[] args) {
// Singleton (not bipartite)
Map<Integer,List<Edge>> graph = new HashMap<>();
addUndirectedEdge(graph,0,0);
displayGraph(graph, 1);
// Prints:
// Graph has 1 node(s) and the following edges:
// 0 -> 0
// 0 -> 0
// This graph is bipartite: false
// Two nodes one edge between them (bipartite)
graph.clear();
addUndirectedEdge(graph, 0, 1);
displayGraph(graph, 2);
// Prints:
// Graph has 2 node(s) and the following edges:
// 0 -> 1
// 1 -> 0
// This graph is bipartite: true
// Triangle graph (not bipartite)
graph.clear();
addUndirectedEdge(graph, 0, 1);
addUndirectedEdge(graph, 1, 2);
addUndirectedEdge(graph, 2, 0);
displayGraph(graph, 3);
// Prints:
// Graph has 3 node(s) and the following edges:
// 0 -> 1
// 0 -> 2
// 1 -> 0
// 1 -> 2
// 2 -> 1
// 2 -> 0
// This graph is bipartite: false
// Disjoint graph is bipartite connected components (altogether not bipartite)
graph.clear();
addUndirectedEdge(graph, 0, 1);
addUndirectedEdge(graph, 2, 3);
displayGraph(graph, 4);
// Prints:
// Graph has 4 node(s) and the following edges:
// 0 -> 1
// 1 -> 0
// 2 -> 3
// 3 -> 2
// This graph is bipartite: false
// Square graph (bipartite)
graph.clear();
addUndirectedEdge(graph,0,1);
addUndirectedEdge(graph,1,2);
addUndirectedEdge(graph,2,3);
addUndirectedEdge(graph,3,0);
displayGraph(graph, 4);
// Prints:
// Graph has 4 node(s) and the following edges:
// 0 -> 1
// 0 -> 3
// 1 -> 0
// 1 -> 2
// 2 -> 1
// 2 -> 3
// 3 -> 2
// 3 -> 0
// This graph is bipartite: true
// Square graph with additional edge (not bipartite)
graph.clear();
addUndirectedEdge(graph,0,1);
addUndirectedEdge(graph,1,2);
addUndirectedEdge(graph,2,3);
addUndirectedEdge(graph,3,0);
addUndirectedEdge(graph,0,2);
displayGraph(graph, 4);
// Prints:
// Graph has 4 node(s) and the following edges:
// 0 -> 1
// 0 -> 3
// 0 -> 2
// 1 -> 0
// 1 -> 2
// 2 -> 1
// 2 -> 3
// 2 -> 0
// 3 -> 2
// 3 -> 0
// This graph is bipartite: false
}
// Helper method to setup graph
private static void addUndirectedEdge( Map <Integer, List <Edge>> graph, int from, int to) {
List <Edge> list = graph.get(from);
if (list == null) {
list = new ArrayList <Edge>();
graph.put(from, list);
}
list.add(new Edge(from, to));
list = graph.get(to);
if (list == null) {
list = new ArrayList <Edge>();
graph.put(to, list);
}
list.add(new Edge(to, from));
}
private static void displayGraph(Map<Integer,List<Edge>> graph, int n) {
System.out.println("Graph has " + n + " node(s) and the following edges:");
for (int i = 0; i < n; i++) {
List<Edge> edges = graph.get(i);
if (edges != null) {
for (Edge e : edges ) {
System.out.println(e.from + " -> " + e.to);
}
}
}
System.out.println("This graph is bipartite: " + (isBipartite(graph, n)!=null) );
System.out.println();
}
}
|
code/graph_algorithms/src/boruvka_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/boruvka_minimum_spanning_tree/boruvka_minimum_spanning_tree.cpp | #include <iostream>
#include <vector>
const int MAXN = 10000;
const int inf = 0x3fffffff;
int nodeCount, edgesCount;
std::vector<std::pair<int, int>> graf[MAXN];
void readGraph()
{
std::cin >> nodeCount >> edgesCount;
for (int i = 0; i < edgesCount; i++)
{
int x, y, w;
std::cin >> x >> y >> w;
graf[x].push_back({y, w});
graf[y].push_back({x, w});
}
}
int parent[MAXN], rank[MAXN];
// Initialize the forest of trees
void initDisjoint()
{
for (int i = 0; i < nodeCount; i++)
{
parent[i] = i;
rank[i] = 0;
}
}
// Get set representative
int getSR(int x)
{
if (x == parent[x])
return x;
return parent[x] = getSR(parent[x]);
}
int areUnited(int x, int y)
{
return getSR(x) == getSR(y);
}
void unite(int x, int y)
{
x = getSR(x);
y = getSR(y);
if (rank[x] > rank[y])
parent[y] = x;
else
{
parent[x] = y;
if (rank[x] == rank[y])
rank[y]++;
}
}
std::pair<int, int> cheapEdge[MAXN];
int solve()
{
int numberOfTrees = nodeCount;
int weightSum = 0;
initDisjoint();
while (numberOfTrees > 1)
{
// initializing cheapest edge to "none"
for (int i = 0; i < nodeCount; i++)
cheapEdge[i].first = -1;
for (int i = 0; i < nodeCount; i++)
for (size_t j = 0; j < graf[i].size(); j++)
{
std::pair<int, int> edge = graf[i][j];
int xsr = getSR(i);
int ysr = getSR(edge.first);
int w = edge.second;
if (xsr == ysr)
continue;
if (cheapEdge[xsr].first == -1 ||
w < graf[cheapEdge[xsr].first][cheapEdge[xsr].second].second)
cheapEdge[xsr] = {i, j};
if (cheapEdge[ysr].first == -1 ||
w < graf[cheapEdge[ysr].first][cheapEdge[ysr].second].second)
cheapEdge[ysr] = {i, j};
}
for (int i = 0; i < nodeCount; i++)
{
int xsr = getSR(i);
if (cheapEdge[xsr].first == -1)
continue;
std::pair<int, int> edge = graf[cheapEdge[xsr].first][cheapEdge[xsr].second];
int ysr = getSR(edge.first);
if (xsr == ysr)
continue;
weightSum += edge.second;
unite(xsr, ysr);
numberOfTrees--;
}
}
return weightSum;
}
int main()
{
readGraph();
int weight = solve();
std::cout << "The weight of the minimum spanning tree is " << weight;
return 0;
}
|
code/graph_algorithms/src/breadth_first_search/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
# Breadth First Search Algorithm (BFS)
In this algorithm, we search for a target node among the neighbouring nodes at a level in the graph before moving to next level.
Thus, it is also called as level order traversal algorithm.
It is similar to the BFS algorithm for a tree. However, it is possible to have cycles in a graph.
Hence, we have to keep track of the visited nodes. We use a boolean visited for this purpose.
## Explanation
```
S ------ level 0
/ | \
/ | \
A B C --- level 1
| | |
| | |
D E F --- level 2
\ | /
\ | /
G ------ level 3
```
Applying BFS algorithm for above graph will give us following output:
S A B C D E F G
## Complexity
Time complexity: O(V+E)
Each node is enqueued and dequeued at most once. Thus O(V) part is justified.
Finding all the adjacent nodes takes O(E) time.
Space complexity: O(V), worst case we need to store all the nodes in the queue.
V - number of nodes
E - number of edges
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/graph_algorithms/src/breadth_first_search/breadth_first_search.c | #include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
int del(struct node** head,int* element);
int add(struct node** head,int element);
//main program
int main()
{
//input no of nodes: Num
int Num;
printf("Enter number of nodes\n");
scanf("%d",&Num);
//create adjacency matrix
int adj[Num][Num];
//input adjacency matrix
printf("Enter adjacency matrix\n");
for(int i=0;i<Num;i++)
{
for(int j=0;j<Num;j++)
{
scanf("%d",&adj[i][j]);
}
}
//BFS traversing
//create a queue
struct node *Queue=NULL;
//create status array and set it to ready state
enum{ready,waiting,processed};
int status[Num];
for(int i=0;i<Num;i++)
{
status[i]=ready;
}
//add first node to queue
add(&Queue,0);
status[0]=waiting;
int node=NULL;
printf("BFS traversing\n");
while(Queue!=NULL)
{
//get a node from queue, display it and change status to processed
del(&Queue,&node);
printf("%d ",node);
status[node]=processed;
//add it's neighbours with status ready to queue
for(int i=0;i<Num;i++)
{
if(adj[node][i]==1 && status[i]==ready)
{
add(&Queue,i);
status[i]=waiting;
}
}
}
printf("\n");
}
//queue functions
int del(struct node** head,int* element)
{
if(*head==NULL)
return 1;
*element=(*head)->data;
struct node* temp;
temp=*head;
*head=(*head)->next;
free(temp);
return 0;
}
int add(struct node** head,int element)
{
if((*head)==NULL)
{
*head=(struct node*)malloc(sizeof(struct node));
(*head)->next=NULL;
(*head)->data=element;
return 0;
}
struct node* temp=*head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=(struct node*)malloc(sizeof(struct node));
if(temp->next==NULL)
return 1;
temp=temp->next;
temp->data=element;
temp->next=NULL;
return 0;
}
|
code/graph_algorithms/src/breadth_first_search/breadth_first_search.cpp | #include <iostream>
#include <map>
#include <set>
#include <queue>
/* Part of Cosmos by OpenGenus Foundation */
void bfs(int start, // the node that we are currently at
std::map<int, std::set<int>>& adjList, // the adjacency list for each node
std::map<int, bool>& visited, // the 'visited' state for each node
std::map<int, int>& distance // the distance from the `start` node
)
{
// First, clear the distance map, so that only nodes that we can actually reach from the `start` appear in it at the end
distance.clear();
// This queue will hold pairs of numbers of the form (nodeNumber, distance)
std::queue<std::pair<int, int>> Q;
// Add the first node with distance 0 to the queue and mark it as visited
Q.push(std::make_pair(start, 0));
visited[start] = true;
// Repeat the algorithm until there are no more nodes left to process
while (!Q.empty())
{
// Take the node from the front of the queue and pop it off the queue
auto entry = Q.front(); Q.pop();
int node = entry.first;
int dist = entry.second;
// Put the distance to this node into the distance map (this is the minimal distance to this node)
distance[node] = dist;
// Iterate over the neighbours of the current node
for (auto neighbour : adjList[node])
if (!visited[neighbour])
{
// Mark the neighbour node as visited
visited[neighbour] = true;
Q.push(std::make_pair(neighbour, dist + 1));
}
}
}
void addEdge(int a, int b, std::map<int, std::set<int>>& adjList)
{
adjList[a].insert(b);
adjList[b].insert(a);
}
int main()
{
/*
* Do a breadth-first search in this graph:
*
* 1--2--4--7
| / \ |
|/ \ |
| 3 5--6
|
| 8--9
*/
std::map<int, std::set<int>> adjList;
std::map<int, bool> visited;
std::map<int, int> dist;
addEdge(1, 2, adjList);
addEdge(1, 3, adjList);
addEdge(2, 3, adjList);
addEdge(2, 4, adjList);
addEdge(2, 5, adjList);
addEdge(4, 7, adjList);
addEdge(5, 6, adjList);
addEdge(6, 7, adjList);
addEdge(8, 9, adjList);
// Set all nodes as unvisited at first
for (int i = 1; i <= 8; i++)
visited[i] = false;
// Perform a bfs from the node `1`
bfs(1, adjList, visited, dist);
// Print the distance to all visited nodes
for (auto entry : dist)
std::cout << "Distance from 1 to " << entry.first << " is " << entry.second << std::endl;
return 0;
}
|
code/graph_algorithms/src/breadth_first_search/breadth_first_search.java | // Java program to print BFS traversal from a given source vertex.
import java.io.*;
import java.util.*;
// Part of Cosmos by OpenGenus Foundation
// This class represents a directed Graph using adjacency list representation
class Bfs
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency Lists
// Constructor of the class
Bfs(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i) {
adj[i] = new LinkedList();
}
}
// Function to add an edge into the Graph
void addEdge(int v,int w) {
adj[v].add(w);
}
// prints BFS traversal from a given source s
void BFS(int s) {
// Mark all the vertices as not visited(By default
// set as false)
boolean visited[] = new boolean[V];
// Create a queue for BFS
LinkedList<Integer> queue = new LinkedList<Integer>();
// Mark the current node as visited and enqueue it
visited[s]=true;
queue.add(s);
while (queue.size() != 0) {
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print( s + " ");
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited and enqueue it
Iterator<Integer> i = adj[s].listIterator();
while( i.hasNext()) {
int n = i.next();
if ( !visited[n] ) {
visited[n] = true;
queue.add(n);
}
}
}
}
// Driver method to
public static void main(String args[]) {
Bfs g = new Bfs(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);
System.out.println("Following is Breadth First Traversal "+"(starting from vertex 2)");
g.BFS(2);
System.out.println();
}
}
|
code/graph_algorithms/src/breadth_first_search/breadth_first_search.py | """ Part of Cosmos by OpenGenus Foundation"""
import collections
"""
Wrapper function for the print function.
Used as the default visitFunc for bfs
"""
def visitPrint(i):
print(i)
"""
A class representing a undirected graph of nodes.
An edge can be added between two nodes by calling addEdge
*This class assumes all edge weights are equal
"""
class Graph:
def __init__(self):
self.adjList = collections.defaultdict(set)
def addEdge(self, node1, node2):
self.adjList[node1].add(node2)
self.adjList[node2].add(node1)
"""
Given a 'start' node and a 'graph', call visitFunc
sequentially on the current node, and then its children
and so forth.
When visiting each node, mark it as visited by adding it to the hashmap.
Then queue up all of its children to be visited next.
"""
def bfs(start, graph, visitFunc=visitPrint):
visited = collections.defaultdict(bool)
queue = collections.deque()
queue.append(start)
while len(queue) > 0:
current = queue.popleft()
if not visited[current]:
visited[current] = True
visitFunc(current)
for neighbor in graph.adjList[current]:
queue.append(neighbor)
# Testing the breadth first search implementation
if __name__ == "__main__":
# Testing on this tree
# 1
# / \
# / \
# 2 3
# / \ / \
# 4 5 6 7
g = Graph()
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(2, 5)
g.addEdge(3, 6)
g.addEdge(3, 7)
print("Test 1:")
bfs(1, g)
print("\nTest2:")
bfs(2, g)
"""Output:
Test 1:
1
2
3
4
5
6
7
Test2:
2
1
4
5
3
6
7
"""
|
code/graph_algorithms/src/breadth_first_search/breadth_first_search.rb | # This class represents a node in a graph.
# It has a NAME and an ID and each node knows which nodes it is connected to.
class GraphNode
require 'set'
@@id = 0
attr_reader :name, :id, :connections
def initialize(name)
@name = name
@id = (@@id += 1)
@connections = Set.new
end
def connect(node)
return false unless node.is_a? GraphNode
@connections << node
end
def equal?(other)
return false unless other.is_a? GraphNode
@name == other.name && @id == other.id
end
def to_s
"<GraphNode:#{name}>"
end
def to_str
to_s
end
end
# A simple function as a default function performed for each node in bfs()
def goalNode?(node)
node.name == 'Goal'
end
# Given a start node and a function or code block this performs a bread first search and will exit upon function or code block returning true, or returns :goal_node_not_found when it has visited the whole graph.
#
# visited is a set containing all nodes that has been checked.
# frontier is a queue were new nodes are appended, making this a breadth first search.
def bfs(start, goal = :goalNode?)
require 'set'
visited = Set.new
frontier = []
frontier << start
until frontier.empty?
current = frontier.shift
next if visited.include? current
visited << current
found = false
found = if block_given?
yield(current)
else
send(goal, current)
end
if !found
current.connections.each do |node|
frontier << node
end
else
return current
end
end
:goal_node_not_found
end
# A small test that will use bfs() for root node First, then for the Second node.
# The bfs accepts a code block, and here we just print each visited node and will never find the goal-node.
#
# The tests output:
# Testing from root node 'First'
# <GraphNode:First>
# <GraphNode:Second>
# <GraphNode:Third>
# <GraphNode:Fourth>
# <GraphNode:Fifth>
# <GraphNode:Goal>
# <GraphNode:Sixth>
# goal_node_not_found
# Testing from second node 'Second'
# <GraphNode:Second>
# <GraphNode:First>
# <GraphNode:Fourth>
# <GraphNode:Fifth>
# <GraphNode:Third>
# <GraphNode:Goal>
# <GraphNode:Sixth>
# goal_node_not_found
def test
puts 'Building Graph for tests...'
# Simple graph
#
# First
# / \
# second third
# / | | \
# fourth fifth goal sixth
#
# Construct graph
first = GraphNode.new 'First'
second = GraphNode.new 'Second'
third = GraphNode.new 'Third'
fourth = GraphNode.new 'Fourth'
fifth = GraphNode.new 'Fifth'
sixth = GraphNode.new 'Sixth'
goal = GraphNode.new 'Goal'
first.connect second
first.connect third
second.connect first
second.connect fourth
second.connect fifth
third.connect first
third.connect goal
third.connect sixth
fourth.connect second
fifth.connect second
goal.connect third
sixth.connect third
# Perform tests
puts "Testing from root node 'First'"
puts(bfs(first) { |node| puts ' ' + node })
puts "Testing from second node 'Second'"
puts(bfs(second) { |node| puts ' ' + node })
end
test if $PROGRAM_NAME == __FILE__
|
code/graph_algorithms/src/breadth_first_search/breadth_first_search.swift | func breadthFirstSearch(_ graph: Graph, source: Node) -> [String] {
var queue = Queue<Node>()
queue.enqueue(source)
var nodesExplored = [source.label]
source.visited = true
while let current = queue.dequeue() {
for edge in current.neighbors {
let neighborNode = edge.neighbor
if !neighborNode.visited {
queue.enqueue(neighborNode)
neighborNode.visited = true
nodesExplored.append(neighborNode.label)
}
}
}
return nodesExplored
}
|
code/graph_algorithms/src/bridge_tree/bridge_tree.cpp | #include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <utility>
using namespace std;
typedef long long ll;
// Part of Cosmos by OpenGenus Foundation
const int MAXN = 1e5 + 5;
vector<int> adj[MAXN], tree[MAXN]; // The bridge edge tree formed from the given graph.
int disc[MAXN], low[MAXN], vis[MAXN];
queue<int> Q[MAXN];
int currTime, n, m, cmpno = 1;
map<pair<int, int>, int> bridge;
void dfs0(int u, int parent)
{
vis[u] = true;
disc[u] = low[u] = currTime++;
for (auto v : adj[u])
{
if (v == parent)
continue;
if (!vis[v])
{
dfs0(v, u);
low[u] = min(low[u], low[v]);
if (low[v] > disc[u])
{
bridge[{u, v}] = 1;
bridge[{v, u}] = 1;
}
}
else
low[u] = min(low[u], disc[v]);
}
return;
}
bool isBridge(int u, int v)
{
return bridge[{u, v}] == 1 && bridge[{v, u}] == 1;
}
void dfs1(int u)
{
int currcmp = cmpno;
Q[currcmp].push(u);
vis[u] = true;
while (!Q[currcmp].empty())
{
int u = Q[currcmp].front();
Q[currcmp].pop();
for (auto v : adj[u])
{
if (vis[v])
continue;
if (isBridge(u, v))
{
cmpno++;
tree[currcmp].push_back(cmpno);
tree[cmpno].push_back(currcmp);
dfs1(v);
}
else
{
Q[currcmp].push(v);
vis[v] = true;
}
}
}
return;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs0(1, -1); // To find bridges
for (size_t i = 0; i < MAXN; ++i)
vis[i] = false;
dfs1(1); // To build bridge tree
for (int i = 1; i <= cmpno; i++)
for (size_t j = 0; j < tree[i].size(); j++)
cout << i << " " << tree[i][j] << endl;
return 0;
}
|
code/graph_algorithms/src/bridges_in_graph/Count_bridges.py | # Python program to find bridges in a given undirected graph
#Complexity : O(V+E)
from collections import defaultdict
#This class represents an undirected 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
self.Time = 0
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
self.graph[v].append(u)
def bridgeUtil(self,u, visited, parent, low, disc,res):
# Mark the current node as visited and print it
visited[u]= True
# Initialize discovery time and low value
disc[u] = self.Time
low[u] = self.Time
self.Time += 1
#Recur for all the vertices adjacent to this vertex
for v in self.graph[u]:
# If v is not visited yet, then make it a child of u
# in DFS tree and recur for it
if visited[v] == False :
parent[v] = u
self.bridgeUtil(v, visited, parent, low, disc,res)
# Check if the subtree rooted with v has a connection to
# one of the ancestors of u
low[u] = min(low[u], low[v])
''' If the lowest vertex reachable from subtree
under v is below u in DFS tree, then u-v is
a bridge'''
if low[v] > disc[u]:
res.append([u,v])
elif v != parent[u]: # Update low value of u for parent function calls.
low[u] = min(low[u], disc[v])
# DFS based function to find all bridges. It uses recursive
# function bridgeUtil()
def bridge(self):
# Mark all the vertices as not visited and Initialize parent and visited,
# and ap(articulation point) arrays
visited = [False] * (self.V)
disc = [float("Inf")] * (self.V)
low = [float("Inf")] * (self.V)
parent = [-1] * (self.V)
res=[]
# Call the recursive helper function to find bridges
# in DFS tree rooted with vertex 'i'
for i in range(self.V):
if visited[i] == False:
self.bridgeUtil(i, visited, parent, low, disc,res)
print(len(res))
# Create a graph given in the above diagram
g1 = Graph(5)
g1.addEdge(1, 0)
g1.addEdge(0, 2)
g1.addEdge(2, 1)
g1.addEdge(0, 3)
g1.addEdge(3, 4)
print("No.of bridges in first graph: ", end="")
g1.bridge()
g2 = Graph(4)
g2.addEdge(0, 1)
g2.addEdge(1, 2)
g2.addEdge(2, 3)
print("No.of bridges in second graph: ", end="")
g2.bridge()
g3 = Graph (7)
g3.addEdge(0, 1)
g3.addEdge(1, 2)
g3.addEdge(2, 0)
g3.addEdge(1, 3)
g3.addEdge(1, 4)
g3.addEdge(1, 6)
g3.addEdge(3, 5)
g3.addEdge(4, 5)
print("No.of bridges in third graph: ", end="")
g3.bridge()
|
code/graph_algorithms/src/bridges_in_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/bridges_in_graph/bridges.cpp | #include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <algorithm>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
#define WHITE 0
#define MAXV 15
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef map<int, int> mii;
vii adjList[MAXV];
vector<string> v_names;
mii dfs_num;
mii dfs_low;
mii dfs_parent;
int dfsNumberCounter;
int dfsRoot;
int rootChildren;
bool articulation_vertex[MAXV];
void articulation(int u)
{
dfs_low[u] = dfs_num[u] = dfsNumberCounter++;
for (vii::iterator it = adjList[u].begin(); it != adjList[u].end(); it++)
{
if (dfs_num[it->first] == WHITE)
{
dfs_parent[it->first] = u;
if (u == dfsRoot)
rootChildren++;
articulation(it->first);
if (dfs_low[it->first] >= dfs_num[u]) // Articulation check
articulation_vertex[u] = true;
if (dfs_low[it->first] > dfs_num[u]) // Bridge check
cout << "Bridge: (" << u << "," << it->first << ") " << endl;
dfs_low[u] = min(dfs_low[u], dfs_low[it->first]);
}
else if (it->first != dfs_parent[u])
dfs_low[u] = min(dfs_low[u], dfs_num[it->first]);
}
}
int main()
{
int V, E, X, Y;
cin >> V >> E;
for (int i = 0; i < E; i++)
{
cin >> X >> Y;
adjList[X].push_back(make_pair(Y, 0));
adjList[Y].push_back(make_pair(X, 0));
}
for (int i = 0; i < V; i++)
if (dfs_num[i] == WHITE)
{
dfsRoot = i;
rootChildren = 0;
articulation(i);
// Special case where the initial vertex is articulation
articulation_vertex[dfsRoot] = (rootChildren > 1);
}
cout << "Articulation Points: " << endl;
for (int i = 0; i < V - 1; i++)
if (articulation_vertex[i])
cout << "Vertex: " << i << endl;
return 0;
}
|
code/graph_algorithms/src/bron_kerbosch_algorithm/bron_kerbosch_algorithm.java | import java.util.*;
public class BronKerbosh {
public static int BronKerbosch(long[] g, long cur, long allowed, long forbidden, int[] weights) {
if (allowed == 0 && forbidden == 0) {
int res = 0;
for (int u = Long.numberOfTrailingZeros(cur); u < g.length; u += Long.numberOfTrailingZeros(cur >> (u + 1)) + 1)
res += weights[u];
return res;
}
if (allowed == 0)
return -1;
int res = -1;
int pivot = Long.numberOfTrailingZeros(allowed | forbidden);
long z = allowed & ~g[pivot];
for (int u = Long.numberOfTrailingZeros(z); u < g.length; u += Long.numberOfTrailingZeros(z >> (u + 1)) + 1) {
res = Math.max(res, BronKerbosch(g, cur | (1L << u), allowed & g[u], forbidden & g[u], weights));
allowed ^= 1L << u;
forbidden |= 1L << u;
}
return res;
}
// random test
public static void main(String[] args) {
Random rnd = new Random(1);
for (int step = 0; step < 1000; step++) {
int n = rnd.nextInt(16) + 1;
long[] g = new long[n];
int[] weights = new int[n];
for (int i = 0; i < n; i++)
weights[i] = rnd.nextInt(1000);
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
if (rnd.nextBoolean()) {
g[i] |= 1L << j;
g[j] |= 1L << i;
}
int res1 = BronKerbosch(g, 0, (1L << n) - 1, 0, weights);
int res2 = maxCliqueSlow(g, weights);
if (res1 != res2)
throw new RuntimeException();
}
}
static int maxCliqueSlow(long[] g, int[] weights) {
int res = 0;
int n = g.length;
for (int set = 0; set < 1 << n; set++) {
boolean ok = true;
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
ok &= (set & (1 << i)) == 0 || (set & (1 << j)) == 0 || (g[i] & (1L << j)) != 0;
if (ok) {
int cur = 0;
for (int i = 0; i < n; i++)
if ((set & (1 << i)) != 0)
cur += weights[i];
res = Math.max(res, cur);
}
}
return res;
}
}
|
code/graph_algorithms/src/centroid_decomposition/centroid_decomposition.cpp | #include <iostream>
#include <vector>
class Graph
{
public:
int ver_;
std::vector<std::vector<int>> adj_;
std::vector<std::vector<int>> centroidTree_;
std::vector<int> sizes_;
std::vector<bool> marked_;
Graph(int num) :
ver_(num),
adj_(num + 1),
centroidTree_(num + 1),
sizes_(num + 1),
marked_(num + 1)
{
}
void addEdge(int x, int y, std::vector<std::vector<int>> &graph);
void calcSizes(int cur, int par, std::vector<std::vector<int>> graph);
int findCentroid(int cur, int par, int vertices, std::vector<std::vector<int>> graph);
void decomposeTree(int cur, int par, int total, int level,
std::vector<std::vector<int>> &Level);
};
void Graph::addEdge(int x, int y, std::vector<std::vector<int>> &graph)
{
if (x < 0 || x > ver_)
{
throw std::out_of_range{"x is out of boundaries"};
}
if (y < 0 || y > ver_)
{
throw std::out_of_range{"y is out of boundaries"};
}
graph[x].push_back(y);
graph[y].push_back(x);
}
void Graph::calcSizes(int cur, int par, std::vector<std::vector<int>> graph)
{
sizes_[cur] = 1;
for (const auto& to : graph[cur])
if (!(to == par || marked_[to]))
{
calcSizes (to, cur, graph);
sizes_[cur] += sizes_[to];
}
}
int Graph::findCentroid(int cur, int par, int vertices, std::vector<std::vector<int>> graph)
{
for (const auto& to : graph[cur])
if (!(to == par || marked_[to]))
if (sizes_[to] > vertices / 2)
return findCentroid(to, cur, vertices, graph);
return cur;
}
void Graph::decomposeTree(int cur, int par, int total, int level,
std::vector<std::vector<int>> &Level)
{
calcSizes(cur, -1, adj_);
int centroid = findCentroid(cur, -1, sizes_[cur], adj_);
Level[level].push_back(centroid);
calcSizes(centroid, -1, adj_);
marked_[centroid] = true;
for (const auto& to : adj_[centroid])
if (!(to == par || marked_[to]))
{
decomposeTree(to, cur, sizes_[to], level + 1, Level);
addEdge(cur, to, centroidTree_);
}
}
void showOutput(std::vector<std::vector<int>> Level)
{
for (int i = 1; Level[i].empty() == false; ++i)
{
std::cout << "Centroids of level " << i << ": ";
bool more_than_1 = false;
for (const auto& j : Level[i])
{
if (more_than_1 == true)
std::cout << ", ";
std::cout << j;
more_than_1 = true;
}
std::cout << '\n';
}
}
int main()
{
std::vector<std::vector<int>> Level(8);
Graph tree(7);
tree.addEdge(1, 2, tree.adj_);
tree.addEdge(1, 3, tree.adj_);
tree.addEdge(2, 4, tree.adj_);
tree.addEdge(4, 5, tree.adj_);
tree.addEdge(4, 6, tree.adj_);
tree.addEdge(2, 7, tree.adj_);
tree.decomposeTree(1, -1, tree.ver_, 1, Level);
showOutput(Level);
return 0;
}
|
code/graph_algorithms/src/centroid_decomposition/centroid_decomposition.java | import java.util.*;
public class CentroidDecomposition {
static void calcSizes(List<Integer>[] tree, int[] size, boolean[] deleted, int u, int p) {
size[u] = 1;
for (int v : tree[u]) {
if (v == p || deleted[v]) continue;
calcSizes(tree, size, deleted, v, u);
size[u] += size[v];
}
}
static int findTreeCentroid(List<Integer>[] tree, int[] size, boolean[] deleted, int u, int p, int vertices) {
for (int v : tree[u]) {
if (v == p || deleted[v]) continue;
if (size[v] > vertices / 2) {
return findTreeCentroid(tree, size, deleted, v, u, vertices);
}
}
return u;
}
static void decompose(List<Integer>[] tree, int[] size, boolean[] deleted, int u, int total) {
calcSizes(tree, size, deleted, u, -1);
int centroid = findTreeCentroid(tree, size, deleted, u, -1, total);
calcSizes(tree, size, deleted, centroid, -1);
deleted[centroid] = true;
System.out.println(centroid);
for (int v : tree[centroid]) {
if (deleted[v]) continue;
decompose(tree, size, deleted, v, size[v]);
}
}
public static void centroidDecomposition(List<Integer>[] tree) {
int n = tree.length;
decompose(tree, new int[n], new boolean[n], 0, n);
}
public static void main(String[] args) {
int n = 4;
List<Integer>[] tree = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);
tree[3].add(0);
tree[0].add(3);
tree[3].add(1);
tree[1].add(3);
tree[3].add(2);
tree[2].add(3);
centroidDecomposition(tree);
}
}
|
code/graph_algorithms/src/channel_assignment/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/connected_components/connected_components.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
*
* Connected Components on undirected graph based of 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;
/*
* getConnectedComponents deep course subroutine.
* Finds the connected component for whom node_ID is the origin node.
*
* @graph The undirected graph.
* @node_ID ID of the origin node.
* @dc_colors Cur graph coloration.
* @connectedComps Connected components array.
* @curComp ID of the connected component that node_ID defines.
*/
static void
connectedComponentsDC(L_Graph* graph, Node_ID node_ID, DC_Color* dc_colors, size_t* connectedComps, size_t curComp)
{
dc_colors[node_ID] = DC_GREY;
connectedComps[node_ID] = curComp;
OneEdge* edge = gNode_EdgesHead(gLG_Node(graph, node_ID));
while (edge != NULL) {
if (dc_colors[gEdge_DestNode(edge)] == DC_WHITE)
connectedComponentsDC(graph, gEdge_DestNode(edge), dc_colors, connectedComps, curComp);
edge = gEdgesList_Next(edge);
}
}
/*
* For each node of the graph, stores in connectedComps the ID of its connected
* component.
* This algorithm executes in thêta(S + A);
*
* @graph The undirected graph.
* @connectedComps An array of at least |S| elements.
* @return Number of connected components.
*/
int
getConnectedComponents(L_Graph* graph, size_t* connectedComps)
{
DC_Color* dc_colors = calloc(gLG_NbNodes(graph), sizeof(*dc_colors));
Node_ID i;
size_t curComp = 0;
for (i = 0; i < gLG_NbNodes(graph); ++i) {
if (dc_colors[i] == DC_WHITE ) {
connectedComponentsDC(graph, i, dc_colors, connectedComps, curComp);
++curComp;
}
}
free(dc_colors);
return (curComp);
}
#define S 5
int
main()
{
L_Graph g;
createLGraph(S, &g);
LGraph_addUEdge(&g, 0, 1);
LGraph_addUEdge(&g, 1, 2);
LGraph_addUEdge(&g, 0, 2);
LGraph_addUEdge(&g, 3, 4);
size_t s[S];
printf("%d\n\n", getConnectedComponents(&g, s));
Node_ID i;
for (i = 0; i < S; ++i)
printf("%d\n", s[i]);
freeLGraph(&g);
return (0);
}
|
code/graph_algorithms/src/count_of_ways_n/count_of_ways_n.cpp | #include <iostream>
#include <vector>
const int MOD = 1000000007;
int size, n;
std::vector< std::vector<long long>> multiple (std::vector< std::vector<long long>> a,
std::vector< std::vector<long long>> b)
{
std::vector< std::vector<long long>> res(size);
for (int i = 0; i < size; i++)
res[i].resize(size);
for (int i = 0; i < size; i++)
for (int l = 0; l < size; l++)
{
long long tmp = 0;
for (int j = 0; j < size; j++)
tmp = (tmp + a[i][j] * b[j][l]) % MOD;
res[i][l] = tmp;
}
return res;
}
std::vector< std::vector<long long>> binPow(std::vector< std::vector<long long>> a, long long power)
{
std::vector< std::vector<long long>> ans(size);
for (int i = 0; i < size; i++)
{
ans[i].resize(size);
ans[i][i] = 1;
}
std::vector< std::vector<long long>> cur = a;
while (power)
{
if (power & 1)
ans = multiple (ans, cur);
cur = multiple (cur, cur);
power /= 2;
}
return ans;
}
int main ()
{
std::cin >> size >> n;
int from, to;
std::cin >> from >> to;
std::vector< std::vector<long long>> graph(size);
for (int i = 0; i < size; i++)
graph[i].resize(size);
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
std::cin >> graph[i][j];
std::cout << binPow(graph, n)[from][to];
}
|
code/graph_algorithms/src/cut_vertices/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/cut_vertices/cut_vertices.cpp | #include <iostream>
#include <vector>
#include <climits>
using namespace std;
typedef long long ll;
// Part of Cosmos by OpenGenus Foundation
const int MAXN = 1e4 + 5;
vector<int> adj[MAXN];
bool vis[MAXN], AP[MAXN];
int n, m, currTime, disc[MAXN];
int low[MAXN]; // low[i] is the minimum of visited currTime of all vertices which are reachable from i.
void init()
{
currTime = 0;
for (int i = 1; i <= n; i++)
{
adj[i].clear(); vis[i] = false; AP[i] = false; disc[i] = 0; low[i] = INT_MAX;
}
}
void dfs(int u, int parent)
{
vis[u] = true;
disc[u] = low[u] = currTime + 1;
int child = 0;
for (auto v : adj[u])
{
if (v == parent)
continue;
if (!vis[v])
{
child = child + 1;
currTime++;
dfs(v, u);
//check if subtree rooted at v has a connection to one of the ancestors of u.
low[u] = min(low[u], low[v]);
if (parent == -1 && child > 1)
AP[u] = true;
if (parent != -1 && low[v] >= disc[u])
AP[u] = true;
}
else
// back edge.
low[u] = min(low[u], disc[v]);
}
}
int main()
{
cin >> n >> m; // n = number of vertices, m = number of edges
init();
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1, -1); //start from any random vertex, make its parent -1.
return 0;
}
|
code/graph_algorithms/src/cycle_directed_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/cycle_directed_graph/cycle_directed_graph.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
*
* 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 <stdlib.h>
#include <stdio.h>
#include <stdint.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 cycle directed detection.
*
* @graph The graph on which we work.
* @node_ID ID of the node on which we will execute the deep course.
* @dc_colors Current coloration of the nodes.
* @return 1 if we find a rear arc. 0 otherwise.
*/
static int
rearArcsDC(L_Graph* graph, Node_ID node_ID, DC_Color* dc_colors)
{
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 (rearArcsDC(graph, gEdge_DestNode(edge), dc_colors))
return (1);
break;
/* Rear arc found ! */
case DC_GREY:
return (1);
break;
default:
break;
}
edge = gEdgesList_Next(edge);
}
dc_colors[node_ID] = DC_BLACK;
return(0);
}
/*
* Let G = (S, A).
* Detects in O(S + A) if the graph contains a directed cycle.
*
* @graph A graph represented by adjacency lists.
* @return 1 if a there's a directed cycle. 0 otherwise.
*/
int
cycleDirectedDetection(L_Graph* graph)
{
DC_Color* dc_colors = calloc(gLG_NbNodes(graph), sizeof(*dc_colors));
Node_ID i;
for (i = 0; i < gLG_NbNodes(graph); ++i) {
/* A sufficient condition for detecting a directed cycle is that a deep course
finds a rear arc. */
if (dc_colors[i] == DC_WHITE && rearArcsDC(graph, i, dc_colors)) {
free(dc_colors);
return (1);
}
}
/* The mentioned condition is also necessary */
free(dc_colors);
return (0);
}
int
main()
{
L_Graph g;
createLGraph(5, &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);
printf("%d\n", cycleDirectedDetection(&g));
freeLGraph(&g);
return (0);
}
|
code/graph_algorithms/src/cycle_directed_graph/cycle_directed_graph.cpp | #include <iostream>
#include <list>
#include <limits.h>
using namespace std;
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic()
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // to add an edge to graph
bool isCyclic(); // returns true if there is a cycle in this graph
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
// This function is a variation of DFSUytil() in http://www.geeksforgeeks.org/archives/18212
bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack)
{
if (visited[v] == false)
{
// Mark the current node as visited and part of recursion stack
visited[v] = true;
recStack[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] && isCyclicUtil(*i, visited, recStack) )
return true;
else if (recStack[*i])
return true;
}
}
recStack[v] = false; // remove the vertex from recursion stack
return false;
}
// Returns true if the graph contains a cycle, else false.
// This function is a variation of DFS() in http://www.geeksforgeeks.org/archives/18212
bool Graph::isCyclic()
{
// Mark all the vertices as not visited and not part of recursion
// stack
bool *visited = new bool[V];
bool *recStack = new bool[V];
for (int i = 0; i < V; i++)
{
visited[i] = false;
recStack[i] = false;
}
// Call the recursive helper function to detect cycle in different
// DFS trees
for (int i = 0; i < V; i++)
if (isCyclicUtil(i, visited, recStack))
return true;
return false;
}
int main()
{
Graph g(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);
if (g.isCyclic())
cout << "Graph contains cycle";
else
cout << "Graph doesn't contain cycle";
return 0;
}
|
code/graph_algorithms/src/cycle_directed_graph/cycle_directed_graph.py | from collections import defaultdict
class Graph:
def __init__(self, v):
self.v = v
self.adj = defaultdict(list)
def add_edge(self, u, v):
self.adj[u].append(v)
def find_parent(self, v, set_map):
return v if set_map[v] == -1 else self.find_parent(set_map[v], set_map)
def union(self, u, v, set_map):
x = self.find_parent(u, set_map)
y = self.find_parent(v, set_map)
set_map[x] = y
def is_cyclic(self):
set_map = [-1] * self.v
visited = [False] * self.v
for u, vs in self.adj.items():
# assume there's only one edge
for v in vs:
x = self.find_parent(u, set_map)
y = self.find_parent(v, set_map)
if x == y:
return True
self.union(x, y, set_map)
# print(set_map)
return False
if __name__ == "__main__":
g = Graph(4)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(2, 3)
print(g.is_cyclic())
g.add_edge(3, 0)
print(g.is_cyclic())
g = Graph(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
print(g.is_cyclic())
|
code/graph_algorithms/src/cycle_directed_graph/cycle_directed_graph_detection.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
*
* 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 <stdlib.h>
#include <stdio.h>
#include <stdint.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 cycle directed detection.
*
* @graph The graph on which we work.
* @node_ID ID of the node on which we will execute the deep course.
* @dc_colors Current coloration of the nodes.
* @return 1 if we find a rear arc. 0 otherwise.
*/
static int
rearArcsDC(L_Graph* graph, Node_ID node_ID, DC_Color* dc_colors)
{
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 (rearArcsDC(graph, gEdge_DestNode(edge), dc_colors))
return (1);
break;
/* Rear arc found ! */
case DC_GREY:
return (1);
break;
default:
break;
}
edge = gEdgesList_Next(edge);
}
dc_colors[node_ID] = DC_BLACK;
return(0);
}
/*
* Let G = (S, A).
* Detects in O(S + A) if the graph contains a directed cycle.
*
* @graph A graph represented by adjacency lists.
* @return 1 if a there's a directed cycle. 0 otherwise.
*/
int
cycleDirectedDetection(L_Graph* graph)
{
DC_Color* dc_colors = calloc(gLG_NbNodes(graph), sizeof(*dc_colors));
Node_ID i;
for (i = 0; i < gLG_NbNodes(graph); ++i) {
/* A sufficient condition for detecting a directed cycle is that a deep course
finds a rear arc. */
if (dc_colors[i] == DC_WHITE && rearArcsDC(graph, i, dc_colors)) {
free(dc_colors);
return (1);
}
}
/* The mentioned condition is also necessary */
free(dc_colors);
return (0);
}
int
main()
{
L_Graph g;
createLGraph(5, &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);
printf("%d\n", cycleDirectedDetection(&g));
freeLGraph(&g);
return (0);
}
|
code/graph_algorithms/src/cycle_undirected_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/cycle_undirected_graph/cycle_undirected_graph.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <list>
#include <limits.h>
using namespace std;
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
bool isCyclicUtil(int v, bool visited[], int parent);
public:
Graph(int V);
void addEdge(int v, int w);
bool isCyclic(); // returns true if there is a cycle
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); //Undirected, so adding edge to both lists
adj[w].push_back(v);
}
bool Graph::isCyclicUtil(int v, bool visited[], int parent)
{
visited[v] = true;
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
{
if (!visited[*i])
{
if (isCyclicUtil(*i, visited, v))
return true;
}
else if (*i != parent)
return true;
}
return false;
}
bool Graph::isCyclic()
{
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int u = 0; u < V; u++)
if (!visited[u])
if (isCyclicUtil(u, visited, -1))
return true;
return false;
}
int main()
{
Graph g1(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 0);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
g1.isCyclic() ? cout << "Graph contains cycle\n" :
cout << "Graph doesn't contain cycle\n";
Graph g2(3);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
g2.isCyclic() ? cout << "Graph contains cycle\n" :
cout << "Graph doesn't contain cycle\n";
return 0;
}
|
code/graph_algorithms/src/cycle_undirected_graph/cycle_undirected_graph.py | class graph:
def __init__(self):
self.neighbors = {}
def add_vertex(self, v):
if v not in self.neighbors:
self.neighbors[v] = []
def add_edge(self, u, v):
self.neighbors[u].append(v)
# if u == v, do not connect u to itself twice
if u != v:
self.neighbors[v].append(u)
def vertices(self):
return list(self.neighbors.keys())
def vertex_neighbors(self, v):
return self.neighbors[v]
def is_cyclic_graph(G):
Q = []
V = G.vertices()
# initially all vertices are unexplored
layer = {v: -1 for v in V}
for v in V:
# v has already been explored; move on
if layer[v] != -1:
continue
# take v as a starting vertex
layer[v] = 0
Q.append(v)
# as long as Q is not empty
while len(Q) > 0:
# get the next vertex u of Q that must be looked at
u = Q.pop(0)
C = G.vertex_neighbors(u)
for z in C:
# if z is being found for the first time
if layer[z] == -1:
layer[z] = layer[u] + 1
Q.append(z)
elif layer[z] >= layer[u]:
return True
return False
|
code/graph_algorithms/src/cycle_undirected_graph/cycle_undirected_graph_check.java | // Java Program to detect cycle in an undirected graph.
// This program performs DFS traversal on the given graph
// represented by a adjacency matrix
// to check for cycles in the graph
import java.util.*;
import java.lang.*;
import java.io.*;
public class CheckCycle
{
private Stack <Integer> stack;
private int adjacencyMatrix[][];
public CheckCycle()
{
stack = new Stack<Integer>();
}
//DFS function
public void dfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
for (int sourcevertex = 1; sourcevertex <= number_of_nodes; sourcevertex++)
{
for (int destinationvertex = 1; destinationvertex <= number_of_nodes; destinationvertex++)
{
adjacencyMatrix[sourcevertex][destinationvertex] = adjacency_matrix[sourcevertex][destinationvertex];
}
}
//Allocating memory for visited nodes
int visited[] = new int[number_of_nodes + 1];
int element = source;
int destination = source;
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
destination = element;
while (destination <= number_of_nodes)
{
if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 1)
{
if (stack.contains(destination))
{
System.out.println("The Graph contains cycle");
return;
}
}
if (adjacencyMatrix[element][destination] == 1 && visited[destination] == 0)
{
stack.push(destination);
visited[destination] = 1;
adjacencyMatrix[element][destination] = 0;
element = destination;
destination = 1;
continue;
}
destination++;
}
stack.pop();
}
}
//The Main function
public static void main(String[] args)
{
int number_of_nodes, source;
Scanner scanner = new Scanner(System.in);
try
{
System.out.println("Enter the number of nodes in the graph");
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
CheckCycle checkCycle = new CheckCycle();
checkCycle.dfs(adjacency_matrix, source);
}catch(InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
}
}
/*
Sample Case ::
Input ::
5
0 0 0 1 0
1 0 1 0 0
0 0 0 0 0
0 1 0 0 1
0 0 1 0 0
1
Output ::
The Graph contains cycle
*/ |
code/graph_algorithms/src/cycle_undirected_graph/cycle_undirected_graph_union_find.cpp | /*this includes code for cheking the cycle is undirected graph using unionfind disjoint data structure
*
* the implementation is very fast
* as it implements unionfind disjoint structure using path-compression and rank heuristics
*/
#include <vector>
#include <cstddef>
int p[1000000]; //stores parent
int rnk[1000000];
int findset(int u) //find set representative of u
{
if (u == p[u])
return u;
return p[u] = findset(p[u]);
}
void unionset(int i, int j) //merge sets with elements i and j
{
int a = findset(i);
int b = findset(j);
if (a != b)
{
if (rnk[a] > rnk[b])
p[b] = a;
else
p[a] = b;
if (rnk[a] == rnk[b])
++rnk[b];
}
}
//note that edgelist can be formed using graph input itself
bool detectcycle(std::vector<std::pair<int, int>> edgelist) // graph given in edge list representation
{
for (std::size_t i = 0; i < edgelist.size(); ++i)
{
std::pair<int, int> u = edgelist[i];
int a = u.first;
int b = u.second;
if (findset(a) == findset(b))
return true;
else
unionset(a, b);
}
return false;
}
|
code/graph_algorithms/src/data_structures/README.md | # Graph data structure
## Adjacency list
Vertices are stored as records or objects, and every vertex stores a list of adjacent vertices. This data structure allows the storage of additional data on the vertices. Additional data can be stored if edges are also stored as objects, in which case each vertex stores its incident edges and each edge stores its incident vertices.
## Adjacency matrix
A two-dimensional matrix, in which the rows represent source vertices and columns represent destination vertices. Data on edges and vertices must be stored externally. Only the cost for one edge can be stored between each pair of vertices.
[wiki page](https://en.wikipedia.org/wiki/Graph_(abstract_data_type)) |
code/graph_algorithms/src/data_structures/adjacency_list.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
|
code/graph_algorithms/src/data_structures/adjacency_list.py | class graph:
def __init__(self):
self.graph={}
def graph_input(self,n):
for i in range(1,n+1):
self.graph.update({i:None})
element=[ ]
choice='y'
while choice=='y':
x=int(input("Enter the edge for vertex %d: "%i))
element.append(x)
self.graph[i]=element
choice=input("Do you want to add more edges? (y/n):")
print("The adjacency list is:")
print(self.graph)
n=int(input("enter total number of nodes: "))
g=graph()
g.graph_input(n)
"""
Output:
enter total number of nodes: 3
Enter the edge for vertex 1: 2
Do you want to add more edges? (y/n):y
Enter the edge for vertex 1: 3
Do you want to add more edges? (y/n):n
Enter the edge for vertex 2: 1
Do you want to add more edges? (y/n):y
Enter the edge for vertex 2: 3
Do you want to add more edges? (y/n):n
Enter the edge for vertex 3: 1
Do you want to add more edges? (y/n):y
Enter the edge for vertex 3: 2
Do you want to add more edges? (y/n):n
The adjacency list is:
{1: [2, 3], 2: [1, 3], 3: [1, 2]}
"""
|
code/graph_algorithms/src/data_structures/adjacency_matrix.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
|
code/graph_algorithms/src/data_structures/adjacency_matrix.py | class graph:
adj=[]
def __init__(self,v,e):
self.v=v
self.e=e
graph.adj=[[0 for i in range(v)] for i in range(v)]
def adj_matrix(self,start,e):
graph.adj[start][e]=1
graph.adj[e][start]=1
def display_adj_matrix(self):
print("The adjacency matrix is: \n")
for i in range (v):
for j in range (v):
print(graph.adj[i][j], end =" ")
print("\n")
choice="y"
v=int(input("Enter number of vertices: "))
e=v
g = graph(v,e)
print("The vertices are: ")
for i in range (v):
print(i, end=' ')
print('\n')
while choice == 'y':
x = int(input("Enter vertex 1: "))
y = int(input("Enter vertex 2: "))
g.adj_matrix(x,y)
choice = input("Do you want to add more edges? (y/n): ")
if choice == "n":
break
g.display_adj_matrix()
"""
Output:
Enter number of vertices: 3
The vertices are:
0 1 2
Enter vertex 1: 1
Enter vertex 2: 2
Do you want to add more edges? (y/n): y
Enter vertex 1: 0
Enter vertex 2: 2
Do you want to add more edges? (y/n): n
The adjacency matrix is:
0 0 1
0 0 1
1 1 0
"""
|
code/graph_algorithms/src/data_structures/adjacency_matrix_c/main.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* How to use matrix-representation graphs.
*/
#include "mgraph_struct.h"
#include <stdio.h>
#define NB_NODES 5
int
main()
{
M_Graph g;
createMGraph(NB_NODES, &g);
int i, j;
for (i = 0; i < NB_NODES; ++i) {
for (j = 0; j < NB_NODES; ++j) {
printf("%d ", MG_get(&g, i, j));
}
printf("\n");
}
MG_set(&g, 0, 0, 1);
MG_set(&g, 1, 2, 1);
MG_set(&g, 2, 3, 1);
printf("\n");
for (i = 0; i < NB_NODES; ++i) {
for (j = 0; j < NB_NODES; ++j) {
printf("%d ", MG_get(&g, i, j));
}
printf("\n");
}
freeMGraph(&g);
return (0);
}
|
code/graph_algorithms/src/data_structures/adjacency_matrix_c/mgraph_struct.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Here we have the definition of a graph using adjacency-matrix representation.
* NB : MG stands for "matrix graph".
*/
#include "mgraph_struct.h"
/*
* Creates a new graph with matrix-list representation.
*
* @n Number of nodes.
* @graph The struct that will hold the graph.
*
* @return 0 on success.
* -1 when malloc error.
*/
int
createMGraph(size_t n, M_Graph* graph)
{
graph->n = n;
graph->matrix = malloc(n * sizeof(*graph->matrix));
if (graph->matrix == NULL)
return (-1);
int i;
for (i = 0; i < n; ++i) {
graph->matrix[i] = calloc(n, sizeof(**graph->matrix));
if (graph->matrix[i] == NULL) {
graph->n = i; /* This indicates to the free routine the number of rows to free */
freeMGraph(graph);
return (-1);
}
}
return (0);
}
/*
* Frees the given graph.
*
* @graph The graph to free.
*/
void
freeMGraph(M_Graph* graph)
{
int i;
for (i = 0; i < graph->n; ++i)
free(graph->matrix[i]);
free(graph->matrix);
graph->n = 0;
}
/*
* Sets M[i][j] to val.
*/
inline void
MG_set(M_Graph* graph, Node_ID i, Node_ID j, EdgeType val)
{
graph->matrix[i][j] = val;
}
/*
* Returns M[i][j];
*/
inline EdgeType
MG_get(M_Graph* graph, Node_ID i, Node_ID j)
{
return (graph->matrix[i][j]);
}
/*
* Returns graph->n;
*/
inline size_t
MG_size(M_Graph* graph)
{
return (graph->n);
}
|
code/graph_algorithms/src/data_structures/adjacency_matrix_c/mgraph_struct.h | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Here we have the definition of a graph using adjacency-matrix representation.
* NB : MG stands for "matrix graph".
*/
#ifndef MGRAPH_STRUCT_H
#define MGRAPH_STRUCT_H
#include <stdlib.h>
/* Change this to change weighting type, if there is one */
typedef int EdgeType;
/* Don't change this, use Node_ID instead of int to refer to nodes */
typedef int Node_ID;
/*
* A Graph struct using adjacency-matrix representation.
* Let G = (S, A).
*/
typedef struct
{
int n; /* |S| */
EdgeType** matrix; /* This will be allocated dynamicaly */
} M_Graph;
/*
* Creates a new graph with matrix-list representation.
*
* @n Number of nodes.
* @graph The struct that will hold the graph.
*
* @return 0 on success.
* -1 when malloc error.
*/
int
createMGraph(size_t n, M_Graph* graph);
/*
* Frees the given graph.
*
* @graph The graph to free.
*/
void
freeMGraph(M_Graph* graph);
/*
* Sets M[i][j] to val.
*/
void
MG_set(M_Graph* graph, Node_ID i, Node_ID j, EdgeType val);
/*
* Returns M[i][j];
*/
EdgeType
MG_get(M_Graph* graph, Node_ID i, Node_ID j);
/*
* Returns graph->n;
*/
size_t
MG_size(M_Graph* graph);
#endif // MGRAPH_STRUCT
|
code/graph_algorithms/src/depth_first_search/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/depth_first_search/depth_first_search.c |
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
int push(struct node** head,int element);
int pop(struct node** head,int* element);
//main program
int main()
{
//input no of nodes: Num
int Num;
printf("Enter number of nodes\n");
scanf("%d",&Num);
//create adjacency matrix
int adj[Num][Num];
//input adjacency matrix
printf("Enter adjacency matrix\n");
for(int i=0;i<Num;i++)
{
for(int j=0;j<Num;j++)
{
scanf("%d",&adj[i][j]);
}
}
//DFS traversing
//create a stack
struct node *Stack=NULL;
//create status array and set it to ready state
enum{ready,waiting,processed};
int status[Num];
for(int i=0;i<Num;i++)
{
status[i]=ready;
}
//add first node to stack
push(&Stack,0);
status[0]=waiting;
int node=NULL;
printf("DFS traversing\n");
while(Stack!=NULL)
{
//get a node from stack, display it and change status to processed
pop(&Stack,&node);
printf("%d ",node);
status[node]=processed;
//add it's neighbours with status ready to stack
for(int i=0;i<Num;i++)
{
if(adj[node][i]==1 && status[i]==ready)
{
push(&Stack,i);
status[i]=waiting;
}
}
}
printf("\n");
}
//stack functions
int push(struct node** head,int element)
{
struct node* temp;
temp=*head;
*head=(struct node*)malloc(sizeof(struct node));
if(head==NULL)
return 1;
(*head)->data=element;
(*head)->next=temp;
return 0;
}
int pop(struct node** head,int* element)
{
if(*head==NULL)
return 1;
*element=(*head)->data;
struct node* temp;
temp=*head;
*head=(*head)->next;
free(temp);
return 0;
}
|
code/graph_algorithms/src/depth_first_search/depth_first_search.cpp | #include <iostream>
#include <map>
#include <set>
/* Part of Cosmos by OpenGenus Foundation */
void dfs(int current, // the node that we are currently at
std::map<int, std::set<int>>& adjList, // the adjacency list for each node
std::map<int, bool>& visited) // the 'visited' state for each node
{
if (visited[current])
return;
visited[current] = true;
for (auto neighbour : adjList[current])
dfs(neighbour, adjList, visited);
}
void addEdge(int a, int b, std::map<int, std::set<int>>& adjList)
{
adjList[a].insert(b);
adjList[b].insert(a);
}
int main()
{
/*
* Do a depth-first search in this graph:
*
* 1--2--4
| /
|/
| 3
|
| 5--6--7
|
| 8
*/
std::map<int, std::set<int>> adjList;
std::map<int, bool> visited;
addEdge(1, 2, adjList);
addEdge(1, 3, adjList);
addEdge(2, 3, adjList);
addEdge(2, 4, adjList);
addEdge(5, 6, adjList);
addEdge(6, 7, adjList);
addEdge(6, 8, adjList);
// Set all nodes as unvisited at first
for (int i = 1; i <= 8; i++)
visited[i] = false;
// Perform a dfs from the node `1`
dfs(1, adjList, visited);
// Print all the visited nodes:
for (int i = 1; i <= 8; i++)
if (visited[i])
std::cout << i << " ";
return 0;
}
|
code/graph_algorithms/src/depth_first_search/depth_first_search.cs | // C# program to print DFS traversal from a given given graph
using System;
using System.Collections.Generic;
// This class represents a directed graph using adjacency list
// representation
public class Graph
{
private int V; // No. of vertices
// Array of lists for Adjacency List Representation
private List<int> []adj;
// Constructor
Graph(int v)
{
V = v;
adj = new List<int>[v];
for (int i = 0; i < v; ++i)
adj[i] = new List<int>();
}
//Function to add an edge into the graph
void addEdge(int v, int w)
{
adj[v].Add(w); // Add w to v's list.
}
// A function used by DFS
void DFSUtil(int v, bool []visited)
{
// Mark the current node as visited and print it
visited[v] = true;
Console.Write(v + " ");
// Recur for all the vertices adjacent to this vertex
foreach(int i in adj[v])
{
int n = i;
if (!visited[n])
DFSUtil(n, visited);
}
}
// The function to do DFS traversal. It uses recursive DFSUtil()
void DFS()
{
// Mark all the vertices as not visited(set as
// false by default in java)
bool []visited = new bool[V];
// Call the recursive helper function to print DFS traversal
// starting from all vertices one by one
for (int i = 0; i < V; ++i)
if (visited[i] == false)
DFSUtil(i, visited);
}
// Driver code
public static void Main(String []args)
{
Graph g = new 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);
Console.WriteLine("Following is Depth First Traversal");
g.DFS();
}
}
|
code/graph_algorithms/src/depth_first_search/depth_first_search.go | package main
import "fmt"
// Part of Cosmos by OpenGenus Foundation
/**************************************
* Structures
**************************************/
// Define set structure (golang has no built-in set)
// Usage:
//
// s := make(set) // Create empty set
// s := set{7: true, 21: true} // Create set with values
// _, exist := s[7] // Check if 7 is in the set
// s[2] = true // Add 2 to the set
// delete(s, 7) // Remove 7 from the set
type set map[int]bool
// Define Graph structure
type Graph struct {
adjList map[int]set
}
// Create a graph and initialize its adjacency list,
// and return a pointer to it.
func createGraph() *Graph {
var g = Graph{}
g.adjList = make(map[int]set)
return &g
}
// Add an edge between the two given nodes.
// If a node does not exist in the graph yet, add it.
func (g *Graph) addEdge(node1 int, node2 int) {
// Check if node1 is already in the graph
if g.adjList[node1] == nil {
// Nope. Add it
g.adjList[node1] = make(set)
}
g.adjList[node1][node2] = true
// Check if node2 is already in the graph
if g.adjList[node2] == nil {
// Nope. Add it
g.adjList[node2] = make(set)
}
g.adjList[node2][node1] = true
}
/**************************************
* Algorithm
**************************************/
// Perform a depth first search from the given node
// and apply the given function to each node.
func dfs(g *Graph, current int, visited set, visitFunction func(int)) {
if _, seen := visited[current]; seen {
return
}
visited[current] = true
visitFunction(current)
for neighbour := range g.adjList[current] {
dfs(g, neighbour, visited, visitFunction)
}
}
/**************************************
* Tests
**************************************/
// Test the dfs algorithm on this graph:
//
// 1
// / \
// / \
// 2 5
// / \ / \
// 3 - 4 6 7
//
// Should output: 1 2 3 4 5 6 7, OR SIMILAR (example: 1 2 4 3 5 7 6)
//
// NOTE: the output order may vary because we used a for range loop,
// and according to the spec (https://golang.org/ref/spec#For_statements):
// "The iteration order over maps is not specified and is not guaranteed
// to be the same from one iteration to the next."
//
// => Output may vary but will always be right from algorithmic POV.
func main() {
graph := createGraph()
graph.addEdge(1, 2)
graph.addEdge(2, 3)
graph.addEdge(2, 4)
graph.addEdge(3, 4)
graph.addEdge(1, 5)
graph.addEdge(5, 6)
graph.addEdge(5, 7)
visited := make(set)
dfs(graph, 1, visited, func(node int) {
fmt.Print(node, " ")
})
} |
code/graph_algorithms/src/depth_first_search/depth_first_search.java | // Java program to print DFS traversal from a given Graph
// Part of Cosmos by OpenGenus Foundation
import java.io.*;
import java.util.*;
// This class represents a directed Dfs using adjacency list representation
class Dfs {
private int V; // No. of vertices
// Array of lists for Adjacency List Representation
private LinkedList<Integer> adj[];
// Constructor of the class
Dfs(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i) {
adj[i] = new LinkedList();
}
}
//Function to add an edge into the Graph
void addEdge(int v, int w) {
adj[v].add(w); // Add w to v's list.
}
// A function used by DFS
void DFSUtil(int v,boolean visited[]) {
// Mark the current node as visited and print it
visited[v] = true;
System.out.print( v + " ");
// Recur for all the vertices adjacent to this vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if ( !visited[n] ) {
DFSUtil(n, visited);
}
}
}
// The function to do DFS traversal. It uses recursive DFSUtil()
void DFS(int v) {
// Mark all the vertices as not visited(set as false by default in java)
boolean visited[] = new boolean[V];
// Call the recursive helper function to print DFS traversal
DFSUtil(v, visited);
}
public static void main(String args[]) {
Dfs g = new Dfs(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);
System.out.println("Following is Depth First Traversal "+ "(starting from vertex 2)");
g.DFS(2);
System.out.println();
}
}
|
code/graph_algorithms/src/depth_first_search/depth_first_search.kt | // Part of Cosmos by OpenGenus Foundation
import java.util.LinkedList
class Dfs(private val vertices: Int) {
// Array of lists for Adjacency List Representation
private val adj: List<LinkedList<Int>> = (0 until vertices).map { LinkedList<Int>() }
// Function to add an edge into the Graph
fun addEdge(vertex: Int, weight: Int) {
adj[vertex].add(weight) // Add weight to vertex's list.
}
// A function used by DFS
private fun dfsUtil(vertex: Int, visited: BooleanArray) {
// Mark the current node as visited and print it
visited[vertex] = true
print("$vertex ")
// Recur for all the vertices adjacent to this vertex
adj[vertex].filter { !visited[it] }.forEach { dfsUtil(it, visited) }
}
// The function to do DFS traversal. It uses recursive DfsUtil()
fun traverse(startVertex: Int) {
// Call the recursive helper function to print DFS traversal
dfsUtil(startVertex, BooleanArray(vertices))
}
}
fun main(args: Array<String>) {
val graph = Dfs(4)
graph.addEdge(0, 1)
graph.addEdge(0, 2)
graph.addEdge(1, 2)
graph.addEdge(2, 0)
graph.addEdge(2, 3)
graph.addEdge(3, 3)
println("Following is Depth First Traversal " + "(starting from vertex 2)")
graph.traverse(2)
println()
} |
code/graph_algorithms/src/depth_first_search/depth_first_search.py | """ Part of Cosmos by OpenGenus Foundation"""
import collections
class Graph:
def __init__(self):
self.adjList = collections.defaultdict(set)
def addEdge(self, node1, node2):
self.adjList[node1].add(node2)
self.adjList[node2].add(node1)
def dfsHelper(current, graph, visited, visitFunc):
if visited[current]:
return
visited[current] = True
visitFunc(current)
for neighbor in graph.adjList[current]:
dfsHelper(neighbor, graph, visited, visitFunc)
def dfs(current, graph, visitFunc):
visited = collections.defaultdict(bool)
dfsHelper(current, graph, visited, visitFunc)
def visitPrint(i):
print(i)
# Testing the depth first search implementation
if __name__ == "__main__":
# Testing on this tree
# 1
# / \
# / \
# 2 3
# / \ / \
# 4 5 6 7
g = Graph()
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(2, 5)
g.addEdge(3, 6)
g.addEdge(3, 7)
print("Test 1:")
dfs(1, g, visitPrint)
print("\nTest2:")
dfs(2, g, visitPrint)
"""Output:
Test 1:
1
2
4
5
3
6
7
Test2:
2
1
3
6
7
4
5
"""
|
code/graph_algorithms/src/depth_first_search/depth_first_search.rb | # This class represents a node in a graph.
# It has a NAME and an ID and each node knows which nodes it is connected to.
class GraphNode
require 'set'
@@id = 0
attr_reader :name, :id, :connections
def initialize(name)
@name = name
@id = (@@id += 1)
@connections = Set.new
end
def connect(node)
return false unless node.is_a? GraphNode
@connections << node
end
def equal?(other)
return false unless other.is_a? GraphNode
@name == other.name && @id == other.id
end
def to_s
"<GraphNode:#{name}>"
end
def to_str
to_s
end
end
# A simple function as a default function performed for each node in dfs()
def goalNode?(node)
node.name == 'Goal'
end
# Given a start node and a function or code block this performs a depth first search and will exit upon function or code block returning true, or returns :goal_node_not_found when it has visited the whole graph.
#
# visited is a set containing all nodes that has been checked.
# frontier is a queue were new nodes are prepended in reverse order, making this a depth first search.
def dfs(start, goal = :goalNode?)
require 'set'
visited = Set.new
frontier = []
frontier << start
until frontier.empty?
current = frontier.shift
next if visited.include? current
visited << current
found = false
found = if block_given?
yield(current)
else
send(goal, current)
end
if !found
current.connections.reverse_each do |node|
frontier.unshift node
end
else
return current
end
end
:goal_node_not_found
end
# A small test that will use dfs() for root node First, then for the Second node.
# The dfs accepts a code block, and here we just print each visited node and will never find the goal-node.
#
# The tests output:
# Building Graph for tests...
# Testing from root node 'First'
# <GraphNode:First>
# <GraphNode:Second>
# <GraphNode:Fourth>
# <GraphNode:Fifth>
# <GraphNode:Third>
# <GraphNode:Goal>
# <GraphNode:Sixth>
# goal_node_not_found
# Testing from second node 'Second'
# <GraphNode:Second>
# <GraphNode:First>
# <GraphNode:Third>
# <GraphNode:Goal>
# <GraphNode:Sixth>
# <GraphNode:Fourth>
# <GraphNode:Fifth>
# goal_node_not_found
def test
puts 'Building Graph for tests...'
# Simple graph
#
# First
# / \
# second third
# / | | \
# fourth fifth goal sixth
#
# Construct graph
first = GraphNode.new 'First'
second = GraphNode.new 'Second'
third = GraphNode.new 'Third'
fourth = GraphNode.new 'Fourth'
fifth = GraphNode.new 'Fifth'
sixth = GraphNode.new 'Sixth'
goal = GraphNode.new 'Goal'
first.connect second
first.connect third
second.connect first
second.connect fourth
second.connect fifth
third.connect first
third.connect goal
third.connect sixth
fourth.connect second
fifth.connect second
goal.connect third
sixth.connect third
# Perform tests
puts "Testing from root node 'First'"
puts(dfs(first) { |node| puts ' ' + node })
puts "Testing from second node 'Second'"
puts(dfs(second) { |node| puts ' ' + node })
end
test if $PROGRAM_NAME == __FILE__
|
code/graph_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/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.c | //for directed acyclig graphs!!
// Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
#include<stdlib.h>
#define INF 999999
typedef struct node graph;
struct node{
int val;
graph *next;
int weight;
};
int src;
int wt_ans,val_ans;
int heap_count;
int flag[1000000];
struct node table[1000000];
struct node a[1000000];
void insert_vertex(int n){
int i;
for(i=1;i<=n;i++){
table[i].next=NULL;
table[i].weight=0;
}
}
void insert_edge(int x,int y,int w){
graph *one;
one=(graph*)malloc(sizeof(graph));
one->val=y;
one->weight=w;
one->next=NULL;
graph *tmp;
if(table[x].next==NULL){
table[x].next=one;
}
else{
tmp=table[x].next;
while(tmp->next!=NULL){
tmp=tmp->next;
}
tmp->next=one;
}
}
void insert_heap(int n){
int l,i;
for(i=1;i<=n;i++){
a[i].weight=INF;
a[i].val=i;
}
}
void update_heap(int x,int y){
graph tmp;
int l,k;
int i;
if(x==src && x!=1){
tmp=a[1];
a[1]=a[x];
a[x]=tmp;
a[1].weight=y;
}
else if(x!=src){
for(i=1;i<=heap_count;i++){
if(a[i].val==x){
k=i;
a[k].weight=y;
}
}
while((a[k/2].weight>a[k].weight)&&(k/2>=1)){
tmp=a[k/2];
a[k/2]=a[k];
a[k]=tmp;
k=k/2;
}
}
}
void extract_heap(int z){
graph tmp;
graph var;
tmp=a[1];
val_ans=tmp.val;
wt_ans=tmp.weight;
flag[a[1].val]=1;
a[1]=a[z];
heap_count--;
int k=1;
while((a[k].weight>a[2*k].weight || a[k].weight > a[2*k+1].weight) && (2*k<=z)){
if((a[k].weight>a[2*k].weight) && (a[k].weight <= a[2*k+1].weight)){
var=a[2*k];
a[2*k]=a[k];
a[k]=var;
k=2*k;
}
else{
var=a[2*k+1];
a[2*k+1]=a[k];
a[k]=var;
k=2*k+1;
}
}
}
int check_heap(int x){
int i,y;
for(i=1;i<=heap_count;i++){
if(a[i].val==x){
y=a[i].weight;
}
}
return y;
}
void print_table(int n){
graph *tmp,*var;
int i,j;
for(i=1;i<=n;i++){
printf("table[%d]",i);
tmp=table[i].next;
while(tmp){
printf("->%d",tmp->val);
tmp=tmp->next;
}
printf("\n");
}
}
int main(){
int n,x,y,w,m;
int t;
int v1,v2;
graph *tmp;
graph *var,*tmp2;
n=4;
m=4;
insert_vertex(n);
int i,j,k,l;
heap_count=n;
for(i=1;i<=n;i++){
flag[i]=0;
}
insert_heap(n);
int src,dest;
src=1;
update_heap(src,0);
while(heap_count>0){
extract_heap(heap_count);
v1=val_ans;
table[v1].weight=wt_ans;
tmp2=table[v1].next;
while(tmp2){
var=tmp2;
if(flag[var->val]==0){
v2=check_heap(var->val);
if(var->weight+table[v1].weight < v2){
update_heap(var->val,(var->weight+table[v1].weight));
}
}
tmp2=tmp2->next;
}
}
int q;
for(q=1;q<=n;q++){
printf("%d to %d = %d\n",src ,q,table[q].weight);
}
return 0;
}
|
code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.cpp | #include <iostream>
#include <vector>
#include <set>
#include <utility>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
const int N = 1E4 + 1;
vector<pair<int, int>> graph[N];
set<pair<int, int>> pq;
int dist[N], vis[N];
int main()
{
int n, m; cin >> n >> m;
while (m--)
{
int u, v, w; cin >> u >> v >> w;
graph[u].push_back({v, w});
}
for (int i = 0; i <= n; i++)
dist[i] = 1E9, vis[i] = 0;
dist[1] = 0;
pq.insert({0, 1});
while (!pq.empty())
{
pair<int, int> p = *pq.begin();
pq.erase(pq.begin());
int u = p.second;
if (vis[u])
continue;
vis[u] = 1;
for (auto k : graph[u])
if (dist[k.first] > (dist[u] + k.second))
{
dist[k.first] = dist[u] + k.second;
pq.insert({dist[k.first], k.first});
}
}
for (int i = 2; i <= n; i++)
cout << dist[i] << " ";
return 0;
}
|
code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.ArrayDeque;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
/**
*
* @author cheikhSall
*/
public class Dijkstra {
public static class Vertex<T> {
T id;
private Map<Vertex, Integer> neighbors;
Integer cost;
public Vertex(T id) {
this.id = id;
this.neighbors = new HashMap<>();
cost = Integer.MAX_VALUE;
}
public Map<Vertex, Integer> getNeighbors() {
return neighbors;
}
public void setNeighbors(Map<Vertex, Integer> neighbors) {
this.neighbors = neighbors;
}
public Number getCost() {
return cost;
}
public void setCost(Integer cost) {
this.cost = cost;
}
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
public void addNeighbor(Vertex neighbor, Integer cost) {
this.neighbors.put(neighbor, cost);
}
}
public static class Graphe<T> {
private Map<T, Vertex> vertices;
public Queue<Vertex> visited;
public Deque<T> paths = new ArrayDeque<>();
public HashMap<T, Integer> distances;
public HashMap<T, T> preds;
public Graphe(Map<T, Vertex> vertices) {
this.vertices = vertices;
this.preds = new HashMap<>();
this.paths = new ArrayDeque<>();
this.distances = new HashMap<>();
this.visited = new PriorityQueue(new Comparator<Vertex>() {
@Override
public int compare(Vertex o1, Vertex o2) {
return o1.cost.compareTo(o2.cost);
}
});
}
public void initDistance() {
this.vertices.keySet().forEach((key) -> {
distances.put(key, Integer.MAX_VALUE);
this.vertices.get(key).setCost(Integer.MAX_VALUE);
});
}
public void initStart(T dep) {
initDistance();
this.distances.put(dep, 0);
}
public Integer getCurrentDistance(T id) {
return this.distances.get(id);
}
public Vertex extractMin() {
Vertex current = null;
try {
current = this.visited.remove();
} catch (Exception e) {
}
return current;
}
public Map<T, Vertex> getVertices() {
return vertices;
}
public void setVertices(Map<T, Vertex> vertices) {
this.vertices = vertices;
}
public void executeOnetoAll(T src) {
this.initStart(src);
Vertex origin = this.vertices.get(src);
if (origin != null) {
origin.setCost(0);
this.visited.add(this.vertices.get(origin.id));
while (!this.visited.isEmpty()) {
Vertex u = this.extractMin();
this.findMinimalDistancesInNeighbor(u);
}
} else {
System.out.println("vertex not existing");
}
}
public void getAllDistances() {
System.out.println("Distances : ");
this.distances.keySet().forEach((vertex) -> {
System.out.println("vertex " + vertex + " cost = " + this.distances.get(vertex).intValue());
});
}
private void findMinimalDistancesInNeighbor(Vertex u) {
u.getNeighbors().keySet().forEach((key) -> {
int cout = (int) u.getNeighbors().get(key);
Vertex v = (Vertex) key;
if (this.getCurrentDistance((T) v.id) > (this.getCurrentDistance((T) u.id) + cout)) {
this.distances.put((T) v.id, (this.getCurrentDistance((T) u.id) + cout));
v.setCost((this.getCurrentDistance((T) u.id) + cout));
this.visited.add(v);
this.preds.put((T) v.id, (T) u.id);
} else {
}
});
}
public void executeOnetoOne(T src, T goal) { // execution de l'algo sur n chemin de depart
this.executeOnetoAll(src);
Vertex origin = this.vertices.get(src);
Vertex dest = this.vertices.get(goal);
if (origin != null && dest != null) {
T step = goal;
while (origin.id != step) {
this.paths.add(step);
step = this.preds.get(step);
}
this.paths.add(src);
this.printPaths(src, goal);
} else {
System.out.println("Path not existing");
}
System.out.println();
}
public void printPaths(T src, T dest) {
System.out.println("Paths : from " + src + " to " + dest);
while (!this.paths.isEmpty()) {
System.out.print(this.paths.removeLast() + ", ");
}
System.out.println();
System.out.println("Total cost : " + this.distances.get(dest));
}
public void printGraph(){
this.vertices.keySet().forEach((key) -> {
this.vertices.get(key).getNeighbors().keySet().forEach((neighbor) -> {
Vertex v = (Vertex) neighbor;
int cost = (int) this.vertices.get(key).getNeighbors().get(neighbor);
System.out.println("("+this.vertices.get(key).id +")" +"---"+ cost+"--->"+"("+v.id+")");
});
});
System.out.println();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Vertex<String> v1 = new Vertex<String>("A");
Vertex<String> v2 = new Vertex<String>("D");
Vertex<String> v3 = new Vertex<String>("E");
Vertex<String> v4 = new Vertex<String>("B");
Vertex<String> v5 = new Vertex<String>("F");
Vertex<String> v6 = new Vertex<String>("C");
v1.addNeighbor(v2, 2);
v1.addNeighbor(v3, 3);
v1.addNeighbor(v4, 1);
v2.addNeighbor(v1, 2);
v2.addNeighbor(v3, 3);
v2.addNeighbor(v5, 4);
v3.addNeighbor(v1, 3);
v3.addNeighbor(v2, 3);
v3.addNeighbor(v4, 8);
v3.addNeighbor(v5, 5);
v4.addNeighbor(v1, 1);
v4.addNeighbor(v6, 6);
v4.addNeighbor(v3, 8);
v5.addNeighbor(v6, 7);
v5.addNeighbor(v3, 5);
v5.addNeighbor(v2, 4);
v6.addNeighbor(v4, 6);
v6.addNeighbor(v5, 7);
Map<String, Vertex> vertices = new HashMap<String, Vertex>();
vertices.put(v1.id, v1);
vertices.put(v2.id, v2);
vertices.put(v3.id, v3);
vertices.put(v4.id, v4);
vertices.put(v5.id, v5);
vertices.put(v6.id, v6);
Graphe<String> graphe = new Graphe<String>(vertices);
System.out.println("GRAPHE :");
graphe.printGraph();
graphe.executeOnetoAll("A");
graphe.executeOnetoOne("A", "C");
graphe.getAllDistances();
graphe.executeOnetoOne("B", "F");
graphe.getAllDistances();
/* Integer entries -------------------------------------------*/
System.out.println();
Vertex< Integer> I1 = new Vertex<Integer>(1);
Vertex<Integer> I2 = new Vertex<Integer>(2);
Vertex<Integer> I3 = new Vertex<Integer>(3);
Vertex<Integer> I4 = new Vertex<Integer>(4);
Vertex<Integer> I5 = new Vertex<Integer>(5);
Vertex<Integer> I6 = new Vertex<Integer>(6);
I1.addNeighbor(I2, 2);
I1.addNeighbor(I3, 3);
I1.addNeighbor(I4, 1);
I2.addNeighbor(I1, 2);
I2.addNeighbor(I3, 3);
I2.addNeighbor(I5, 4);
I3.addNeighbor(I1, 3);
I3.addNeighbor(I2, 3);
I3.addNeighbor(I4, 8);
I3.addNeighbor(I5, 5);
I4.addNeighbor(I1, 1);
I4.addNeighbor(I6, 6);
I4.addNeighbor(I3, 8);
I5.addNeighbor(I6, 7);
I5.addNeighbor(I3, 5);
I5.addNeighbor(I2, 4);
I6.addNeighbor(I4, 6);
I6.addNeighbor(I5, 7);
Map<Integer, Vertex> vertices2 = new HashMap<Integer, Vertex>();
vertices2.put(I1.id, I1);
vertices2.put(I2.id, I2);
vertices2.put(I3.id, I3);
vertices2.put(I4.id, I4);
vertices2.put(I5.id, I5);
vertices2.put(I6.id, I6);
Graphe<Integer> graphe2 = new Graphe<Integer>(vertices2);
System.out.println("GRAPHE :");
graphe2.printGraph();
graphe2.executeOnetoAll(1);
graphe2.executeOnetoOne(4, 5);
graphe2.getAllDistances();
/**
* ** OUTPUT *****
GRAPHE :
(A)---1--->(B)
(A)---2--->(D)
(A)---3--->(E)
(B)---6--->(C)
(B)---1--->(A)
(B)---8--->(E)
(C)---6--->(B)
(C)---7--->(F)
(D)---4--->(F)
(D)---2--->(A)
(D)---3--->(E)
(E)---8--->(B)
(E)---5--->(F)
(E)---3--->(D)
(E)---3--->(A)
(F)---7--->(C)
(F)---4--->(D)
(F)---5--->(E)
Paths : from A to C
A, B, C,
Total cost : 7
Distances :
vertex A cost = 0
vertex B cost = 1
vertex C cost = 7
vertex D cost = 2
vertex E cost = 3
vertex F cost = 6
Paths : from B to F
B, A, D, F,
Total cost : 7
Distances :
vertex A cost = 1
vertex B cost = 0
vertex C cost = 6
vertex D cost = 3
vertex E cost = 4
vertex F cost = 7
GRAPHE :
(1)---3--->(3)
(1)---2--->(2)
(1)---1--->(4)
(2)---3--->(3)
(2)---4--->(5)
(2)---2--->(1)
(3)---5--->(5)
(3)---3--->(2)
(3)---8--->(4)
(3)---3--->(1)
(4)---8--->(3)
(4)---1--->(1)
(4)---6--->(6)
(5)---5--->(3)
(5)---4--->(2)
(5)---7--->(6)
(6)---7--->(5)
(6)---6--->(4)
Paths : from 4 to 5
4, 1, 2, 5,
Total cost : 7
Distances :
vertex 1 cost = 1
vertex 2 cost = 3
vertex 3 cost = 4
vertex 4 cost = 0
vertex 5 cost = 7
vertex 6 cost = 6
*/
}
}
|
code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.js | /**
* Part of Cosmos by OpenGenus
* Javascript program for Dijkstra's single
* source shortest path algorithm. The program is
* for adjacency matrix representation of the graph
*/
class Graph {
constructor(graph) {
this.V = graph.length;
this.graph = graph;
}
printSolution(dist) {
console.log("Vertex tDistance from source");
for (let v = 0; v < this.V; v++) {
console.log(`${v}, t, ${dist[v]}`);
}
}
// A utility function to find the vertex with
// minimum distance value, from the set of vertices
// not yet included in shortest path tree
minDistance(dist, shortestPathSet) {
let min = Infinity;
let min_index;
for (let i = 0; i < this.V; i++) {
if (dist[i] < min && !shortestPathSet[i]) {
min = dist[i];
min_index = i;
}
}
return min_index;
}
// Funtion that implements Dijkstra's single source
// shortest path algorithm for a graph represented
// using adjacency matrix representation
dijkstra(src = 0) {
let dist = Array(this.V).fill(Infinity);
let shortestPathSet = Array(this.V).fill(false);
dist[src] = 0;
for (let i = 0; i < this.V; i++) {
// Pick the minimum distance vertex from
// the set of vertices not yet processed.
// u is always equal to src in first iteration
let u = this.minDistance(dist, shortestPathSet);
// Put the minimum distance vertex in the
// shotest path tree
shortestPathSet[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 (let v = 0; v < this.V; v++) {
if (
this.graph[u][v] > 0 &&
!shortestPathSet[v] &&
dist[v] > dist[u] + this.graph[u][v]
) {
dist[v] = dist[u] + this.graph[u][v];
}
}
}
this.printSolution(dist);
}
}
g = new Graph([
[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]);
g.dijkstra();
|
code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.py | # Python program for Dijkstra's single
# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph
# Library for INT_MAX
import sys
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
def printSolution(self, dist):
print("Vertex tDistance from Source")
for node in range(self.V):
print(node, "t", dist[node])
# A utility function to find the vertex with
# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minDistance(self, dist, sptSet):
# Initilaize minimum distance for next node
min = sys.maxsize
# Search not nearest vertex not in the
# shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
# Funtion that implements Dijkstra's single source
# shortest path algorithm for a graph represented
# using adjacency matrix representation
def dijkstra(self, src):
dist = [sys.maxsize] * self.V
dist[src] = 0
sptSet = [False] * self.V
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.minDistance(dist, sptSet)
# Put the minimum distance vertex in the
# shotest path tree
sptSet[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):
if (
self.graph[u][v] > 0
and sptSet[v] == False
and dist[v] > dist[u] + self.graph[u][v]
):
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [
[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0],
]
g.dijkstra(0)
|
code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path_efficient.py | # Title: Dijkstra's Algorithm for finding single source shortest path from scratch
# Author: Shubham Malik
# References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
# Part of Cosmos by OpenGenus Foundation
import math
import sys
class PriorityQueue:
# Based on Min Heap
def __init__(self):
self.cur_size = 0
self.array = []
self.pos = {} # To store the pos of node in array
def isEmpty(self):
return self.cur_size == 0
def min_heapify(self, idx):
lc = self.left(idx)
rc = self.right(idx)
if lc < self.cur_size and self.array(lc)[0] < self.array(idx)[0]:
smallest = lc
else:
smallest = idx
if rc < self.cur_size and self.array(rc)[0] < self.array(smallest)[0]:
smallest = rc
if smallest != idx:
self.swap(idx, smallest)
self.min_heapify(smallest)
def insert(self, tup):
# Inserts a node into the Priority Queue
self.pos[tup[1]] = self.cur_size
self.cur_size += 1
self.array.append((sys.maxsize, tup[1]))
self.decrease_key((sys.maxsize, tup[1]), tup[0])
def extract_min(self):
# Removes and returns the min element at top of priority queue
min_node = self.array[0][1]
self.array[0] = self.array[self.cur_size - 1]
self.cur_size -= 1
self.min_heapify(1)
del self.pos[min_node]
return min_node
def left(self, i):
# returns the index of left child
return 2 * i + 1
def right(self, i):
# returns the index of right child
return 2 * i + 2
def par(self, i):
# returns the index of parent
return math.floor(i / 2)
def swap(self, i, j):
# swaps array elements at indices i and j
# update the pos{}
self.pos[self.array[i][1]] = j
self.pos[self.array[j][1]] = i
temp = self.array[i]
self.array[i] = self.array[j]
self.array[j] = temp
def decrease_key(self, tup, new_d):
idx = self.pos[tup[1]]
# assuming the new_d is atmost old_d
self.array[idx] = (new_d, tup[1])
while idx > 0 and self.array[self.par(idx)][0] > self.array[idx][0]:
self.swap(idx, self.par(idx))
idx = self.par(idx)
class Graph:
def __init__(self, num):
self.adjList = {} # To store graph: u -> (v,w)
self.num_nodes = num # Number of nodes in graph
# To store the distance from source vertex
self.dist = [0] * self.num_nodes
self.par = [-1] * self.num_nodes # To store the path
def add_edge(self, u, v, w):
# Edge going from node u to v and v to u with weight w
# u (w)-> v, v (w) -> u
# Check if u already in graph
if u in self.adjList.keys():
self.adjList[u].append((v, w))
else:
self.adjList[u] = [(v, w)]
# Assuming undirected graph
if v in self.adjList.keys():
self.adjList[v].append((u, w))
else:
self.adjList[v] = [(u, w)]
def show_graph(self):
# u -> v(w)
for u in self.adjList:
print(
u,
"->",
" -> ".join(str("{}({})".format(v, w)) for v, w in self.adjList[u]),
)
def dijkstra(self, src):
# Flush old junk values in par[]
self.par = [-1] * self.num_nodes
# src is the source node
self.dist[src] = 0
Q = PriorityQueue()
Q.insert((0, src)) # (dist from src, node)
for u in self.adjList.keys():
if u != src:
self.dist[u] = sys.maxsize # Infinity
self.par[u] = -1
while not Q.isEmpty():
u = Q.extract_min() # Returns node with the min dist from source
# Update the distance of all the neighbours of u and
# if their prev dist was INFINITY then push them in Q
for v, w in self.adjList[u]:
new_dist = self.dist[u] + w
if self.dist[v] > new_dist:
if self.dist[v] == sys.maxsize:
Q.insert((new_dist, v))
else:
Q.decrease_key((self.dist[v], v), new_dist)
self.dist[v] = new_dist
self.par[v] = u
# Show the shortest distances from src
self.show_distances(src)
def show_distances(self, src):
print("Distance from node: {}".format(src))
for u in range(self.num_nodes):
print("Node {} has distance: {}".format(u, self.dist[u]))
def show_path(self, src, dest):
# To show the shortest path from src to dest
# WARNING: Use it *after* calling dijkstra
path = []
cost = 0
temp = dest
# Backtracking from dest to src
while self.par[temp] != -1:
path.append(temp)
if temp != src:
for v, w in self.adjList[temp]:
if v == self.par[temp]:
cost += w
break
temp = self.par[temp]
path.append(src)
path.reverse()
print("----Path to reach {} from {}----".format(dest, src))
for u in path:
print("{}".format(u), end=" ")
if u != dest:
print("-> ", end="")
print("\nTotal cost of path: ", cost)
if __name__ == "__main__":
graph = Graph(9)
graph.add_edge(0, 1, 4)
graph.add_edge(0, 7, 8)
graph.add_edge(1, 2, 8)
graph.add_edge(1, 7, 11)
graph.add_edge(2, 3, 7)
graph.add_edge(2, 8, 2)
graph.add_edge(2, 5, 4)
graph.add_edge(3, 4, 9)
graph.add_edge(3, 5, 14)
graph.add_edge(4, 5, 10)
graph.add_edge(5, 6, 2)
graph.add_edge(6, 7, 1)
graph.add_edge(6, 8, 6)
graph.add_edge(7, 8, 7)
graph.show_graph()
graph.dijkstra(0)
graph.show_path(0, 4)
# OUTPUT
# 0 -> 1(4) -> 7(8)
# 1 -> 0(4) -> 2(8) -> 7(11)
# 7 -> 0(8) -> 1(11) -> 6(1) -> 8(7)
# 2 -> 1(8) -> 3(7) -> 8(2) -> 5(4)
# 3 -> 2(7) -> 4(9) -> 5(14)
# 8 -> 2(2) -> 6(6) -> 7(7)
# 5 -> 2(4) -> 3(14) -> 4(10) -> 6(2)
# 4 -> 3(9) -> 5(10)
# 6 -> 5(2) -> 7(1) -> 8(6)
# Distance from node: 0
# Node 0 has distance: 0
# Node 1 has distance: 4
# Node 2 has distance: 12
# Node 3 has distance: 19
# Node 4 has distance: 21
# Node 5 has distance: 11
# Node 6 has distance: 9
# Node 7 has distance: 8
# Node 8 has distance: 14
# ----Path to reach 4 from 0----
# 0 -> 7 -> 6 -> 5 -> 4
# Total cost of path: 21
|
code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path_gnu_fast.cpp | #include <climits>
#include <ext/pb_ds/priority_queue.hpp>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
using namespace __gnu_pbds;
template <class X, class C = greater<X>>
using heap = __gnu_pbds::priority_queue<X, C>;
vector<heap<pair<int, int>>::point_iterator> pt;
vector<int> d;
vector<vector<pair<int, int>>> g;
void dijkstra(int s)
{
fill(d.begin(), d.end(), INT_MAX);
d[s] = 0;
heap<pair<int, int>> q;
pt[s] = q.push(make_pair(d[s], s));
while (!q.empty())
{
auto v = q.top().second;
q.pop();
for (auto x : g[v])
if (d[v] + x.second < d[x.first])
{
d[x.first] = d[v] + x.second;
if (pt[x.first] != nullptr)
q.modify(pt[x.first], make_pair(d[x.first], x.first));
else
q.push(make_pair(d[x.first], x.first));
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
d.resize(n);
g.resize(n);
pt.resize(n);
for (int i = 0; i < m; i++)
{
int x, y, w;
cin >> x >> y >> w;
// vertices must be in range [0, n)
x--;
y--;
g[x].push_back({y, w});
g[y].push_back({x, w});
}
int s;
cin >> s;
s--;
dijkstra(s);
// d[i] == INT_MAX then there is no way between s and i
for (auto x : d)
cout << x << ' ';
return 0;
}
|
code/graph_algorithms/src/dinic_maximum_flow/dinic_maximum_flow.cpp | #include <vector>
#include <queue>
#include <cstring>
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
struct edge
{
int to;
int cap;
int rev;
};
class dinic
{
private:
int INF;
std::vector<edge> G[100000];
int level[100000];
int iter[100000];
public:
dinic();
void add_edge(int from, int to, int cap);
void bfs(int s);
int dfs(int v, int t, int f);
int maximum_flow(int s, int t);
};
dinic::dinic()
{
INF = 0x7fffffff;
std::fill(level, level + 100000, 0);
std::fill(iter, iter + 100000, 0);
}
void dinic::add_edge(int from, int to, int cap)
{
G[from].push_back((edge){to, cap, (int)G[to].size()});
G[to].push_back((edge){from, 0, (int)G[from].size() - 1});
}
void dinic::bfs(int s)
{
std::memset(level, -1, sizeof(level));
std::queue<int> que;
level[s] = 0;
que.push(s);
while (!que.empty())
{
int v = que.front();
que.pop();
for (int i = 0; i < (int)G[v].size(); i++)
{
edge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0)
{
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int dinic::dfs(int v, int t, int f)
{
if (v == t)
return f;
for (int &i = iter[v]; i < (int)G[v].size(); i++)
{
edge &e = G[v][i];
if (e.cap > 0 && level[v] < level[e.to])
{
int d = dfs(e.to, t, std::min(f, e.cap));
if (d > 0)
{
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int dinic::maximum_flow(int s, int t)
{
int flow = 0;
for (;;)
{
bfs(s);
if (level[t] < 0)
return flow;
std::memset(iter, 0, sizeof(iter));
int f;
while ((f = dfs(s, t, INF)) > 0)
flow += f;
}
}
|
code/graph_algorithms/src/eulerian_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/eulerian_path/eulerian_path.java | // A Java program to check if a given graph is Eulerian or not
import java.io.*;
import java.util.*;
import java.util.LinkedList;
class Graph
{
private int V; // vertices
// Adjacency List Representation
private LinkedList<Integer> adj[];
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w)
{
adj[v].add(w);
adj[w].add(v);
}
void DFSUtil(int v,boolean visited[])
{
// Mark the current node as visited
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}
// Method to check if all non-zero degree vertices are
// connected. It mainly does DFS traversal starting from
boolean isConnected()
{
// Mark all the vertices as not visited
boolean visited[] = new boolean[V];
int i;
for (i = 0; i < V; i++)
visited[i] = false;
// Find a vertex with non-zero degree
for (i = 0; i < V; i++)
if (adj[i].size() != 0)
break;
// If there are no edges in the graph, return true
if (i == V)
return true;
// Start DFS traversal from a vertex with non-zero degree
DFSUtil(i, visited);
// Check if all non-zero degree vertices are visited
for (i = 0; i < V; i++)
if (visited[i] == false && adj[i].size() > 0)
return false;
return true;
}
/* The function returns one of the following values
0 --> If grpah is not Eulerian
1 --> If graph has an Euler path (Semi-Eulerian)
2 --> If graph has an Euler Circuit (Eulerian) */
int isEulerian()
{
// Check if all non-zero degree vertices are connected
if (isConnected() == false)
return 0;
// Count vertices with odd degree
int odd = 0;
for (int i = 0; i < V; i++)
if (adj[i].size()%2!=0)
odd++;
// If count is more than 2, then graph is not Eulerian
if (odd > 2)
return 0;
// If odd count is 2, then semi-eulerian.
// If odd count is 0, then eulerian
// Note that odd count can never be 1 for undirected graph
return (odd==2)? 1 : 2;
}
// Function to run test cases
void test()
{
int res = isEulerian();
if (res == 0)
System.out.println("graph is not Eulerian");
else if (res == 1)
System.out.println("graph has a Euler path");
else
System.out.println("graph has a Euler cycle");
}
public static void main(String args[])
{
Graph g1 = new Graph(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 1);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
g1.test();
}
} |
code/graph_algorithms/src/eulerian_path/eulerian_path.py | # Part of Cosmos by OpenGenus Foundation
# Python program to check if a given graph is Eulerian of not using eulerian path identification
# Complexity : O(V+E)
from collections import defaultdict
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)
self.graph[v].append(u)
# A function used by isConnected
def DFSUtil(self, v, visited):
# 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.DFSUtil(i, visited)
def isConnected(self):
# Mark all the vertices as not visited
visited = [False] * (self.V)
# Find a vertex with non-zero degree
for i in range(self.V):
if len(self.graph[i]) > 1:
break
# If there are no edges in the graph, return true
if i == self.V - 1:
return True
# Start DFS traversal from a vertex with non-zero degree
self.DFSUtil(i, visited)
# Check if all non-zero degree vertices are visited
for i in range(self.V):
if visited[i] == False and len(self.graph[i]) > 0:
return False
return True
def isEulerian(self):
# Check if all non-zero degree vertices are connected
if self.isConnected() == False:
return 0
else:
# Count vertices with odd degree
odd = 0
for i in range(self.V):
if len(self.graph[i]) % 2 != 0:
odd += 1
if odd == 0:
return 2
elif odd == 2:
return 1
elif odd > 2:
return 0
# Function to run test cases
def test(self):
res = self.isEulerian()
if res == 0:
print("graph is not Eulerian")
elif res == 1:
print("graph has a Euler path")
else:
print("graph has a Euler cycle")
# Creating an example graph for implementation
g1 = Graph(5)
g1.addEdge(1, 0)
g1.addEdge(0, 2)
g1.addEdge(2, 1)
g1.addEdge(0, 3)
g1.addEdge(3, 4)
g1.test()
g2 = Graph(5)
g2.addEdge(1, 0)
g2.addEdge(0, 2)
g2.addEdge(2, 1)
g2.addEdge(0, 3)
g2.addEdge(3, 4)
g2.addEdge(4, 0)
g2.test()
g3 = Graph(5)
g3.addEdge(1, 0)
g3.addEdge(0, 2)
g3.addEdge(2, 1)
g3.addEdge(0, 3)
g3.addEdge(3, 4)
g3.addEdge(1, 3)
g3.test()
g4 = Graph(3)
g4.addEdge(0, 1)
g4.addEdge(1, 2)
g4.addEdge(2, 0)
g4.test()
g5 = Graph(3)
g5.test()
|
code/graph_algorithms/src/fleury_algorithm_euler_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/floyd_warshall_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/floyd_warshall_algorithm/floyd_warshall.go | package graph
import "math"
// WeightedGraph defining matrix to use 2d array easier
type WeightedGraph [][]float64
// Defining maximum value. If two vertices share this value, it means they are not connected
var Inf = math.Inf(1)
// FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm
func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given graph
result := make(WeightedGraph, numVertices)
for i := 0; i < numVertices; i++ {
result[i] = make([]float64, numVertices)
for j := 0; j < numVertices; j++ {
result[i][j] = graph[i][j]
}
}
// Running over the result matrix and following the algorithm
for k := 0; k < numVertices; k++ {
for i := 0; i < numVertices; i++ {
for j := 0; j < numVertices; j++ {
// If there is a less costly path from i to j node, remembering it
if result[i][j] > result[i][k]+result[k][j] {
result[i][j] = result[i][k] + result[k][j]
}
}
}
}
return result
} |
code/graph_algorithms/src/floyd_warshall_algorithm/floyd_warshall_algorithm.c | // C Program for Floyd Warshall Algorithm
// Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
// Number of vertices in the graph
#define V 4
/* Define Infinite as a large enough value. This value will be used
for vertices not connected to each other */
#define INF 99999
// A function to print the solution matrix
void printSolution(int dist[][V]);
// Solves the all-pairs shortest path problem using Floyd Warshall algorithm
void floydWarshall (int graph[][V]) {
/* dist[][] will be the output matrix that will finally have the shortest
distances between every pair of vertices */
int dist[V][V], i, j, k;
/* Initialize the solution matrix same as input graph matrix. Or
we can say the initial values of shortest distances are based
on shortest paths considering no intermediate vertex. */
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
dist[i][j] = graph[i][j];
}
}
/* Add all vertices one by one to the set of intermediate vertices.
---> Before start of a iteration, we have shortest distances between all
pairs of vertices such that the shortest distances consider only the
vertices in set {0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of a iteration, vertex no. k is added to the set of
intermediate vertices and the set becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
// Print the shortest distance matrix
printSolution(dist);
}
/* A utility function to print solution */
void printSolution(int dist[][V]) {
printf ("Following matrix shows the shortest distances"
" between every pair of vertices \n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf ("%7d", dist[i][j]);
}
printf("\n");
}
}
// driver program to test above function
int main() {
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3 */
int graph[V][V] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
// Print the solution
floydWarshall(graph);
return 0;
}
|
code/graph_algorithms/src/floyd_warshall_algorithm/floyd_warshall_algorithm.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <cstdio>
#include <algorithm>
using namespace std;
#define INF 1000000000
void floydWarshall(int vertex, int adjacencyMatrix[][4])
{
// calculating all pair shortest path
for (int k = 0; k < vertex; k++)
for (int i = 0; i < vertex; i++)
for (int j = 0; j < vertex; j++)
// 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
adjacencyMatrix[i][j] = min( adjacencyMatrix[i][j],
adjacencyMatrix[i][k] + adjacencyMatrix[k][j] );
// pretty print the graph
printf("o/d"); // o/d means the leftmost row is the origin vertex
// and the topmost column as destination vertex
for (int i = 0; i < vertex; i++)
printf("\t%d", i + 1);
printf("\n");
for (int i = 0; i < vertex; i++)
{
printf("%d", i + 1);
for (int j = 0; j < vertex; j++)
printf("\t%d", adjacencyMatrix[i][j]);
printf("\n");
}
}
int main()
{
/*
* 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
*/
int adjacencyMatrix[][4] = {
{ 0, 1, 3, INF},
{ 1, 0, 1, INF},
{ 3, 1, 0, 2},
{INF, INF, 2, 0}
};
floydWarshall(4, adjacencyMatrix);
}
|
code/graph_algorithms/src/floyd_warshall_algorithm/floyd_warshall_algorithm.java | import java.util.*;
import java.lang.*;
import java.io.*;
// Part of Cosmos by OpenGenus Foundation
class FloydWarshall{
final static int INF = 99999, V = 4;
void floydWarshall(int graph[][])
{
int dist[][] = new int[V][V];
int i, j, k;
/* Initialize the solution matrix same as input graph matrix.
Or we can say the initial values of shortest distances
are based on shortest paths considering no intermediate
vertex. */
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
/* Add all vertices one by one to the set of intermediate
vertices.
---> Before start of a iteration, we have shortest
distances between all pairs of vertices such that
the shortest distances consider only the vertices in
set {0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of a iteration, vertex no. k is added
to the set of intermediate vertices and the set
becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++)
{
// Pick all vertices as source one by one
for (i = 0; i < V; i++)
{
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++)
{
// If vertex k is on the shortest path from
// i to j, then update the value of dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
// Print the shortest distance matrix
printSolution(dist);
}
void printSolution(int dist[][])
{
System.out.println("Following matrix shows the shortest "+
"distances between every pair of vertices");
for (int i=0; i<V; ++i)
{
for (int j=0; j<V; ++j)
{
if (dist[i][j]==INF)
System.out.print("INF ");
else
System.out.print(dist[i][j]+" ");
}
System.out.println();
}
}
// Driver program to test above function
public static void main (String[] args)
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3 */
int graph[][] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
FloydWarshall a = new FloydWarshall();
// Print the solution
a.floydWarshall(graph);
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.