Skip to content

Commit 0d202a6

Browse files
authored
Merge branch 'master' into master
2 parents c14d684 + e493eb2 commit 0d202a6

File tree

8 files changed

+594
-39
lines changed

8 files changed

+594
-39
lines changed

DIRECTORY.md

+4
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@
107107
* [ConnectedComponent](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java)
108108
* [Cycles](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java)
109109
* [DijkstraAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java)
110+
* [EdmondsBlossomAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java)
110111
* [FloydWarshall](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java)
111112
* [FordFulkerson](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/FordFulkerson.java)
112113
* [Graphs](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java)
@@ -265,6 +266,7 @@
265266
* [ActivitySelection](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java)
266267
* [CoinChange](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java)
267268
* [FractionalKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java)
269+
* [GaleShapley](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java)
268270
* [JobSequencing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java)
269271
* [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java)
270272
* io
@@ -658,6 +660,7 @@
658660
* graphs
659661
* [BoruvkaAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java)
660662
* [DijkstraAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java)
663+
* [EdmondsBlossomAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithmTest.java)
661664
* [FordFulkersonTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/FordFulkersonTest.java)
662665
* [HamiltonianCycleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java)
663666
* [KosarajuTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java)
@@ -749,6 +752,7 @@
749752
* [ActivitySelectionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java)
750753
* [CoinChangeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java)
751754
* [FractionalKnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java)
755+
* [GaleShapleyTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java)
752756
* [JobSequencingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java)
753757
* [MinimizingLatenessTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessTest.java)
754758
* io

src/main/java/com/thealgorithms/backtracking/MColoring.java

+43-24
Original file line numberDiff line numberDiff line change
@@ -7,71 +7,90 @@
77
import java.util.Set;
88

99
/**
10+
* Node class represents a graph node. Each node is associated with a color
11+
* (initially 1) and contains a set of edges representing its adjacent nodes.
12+
*
1013
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
1114
*/
1215
class Node {
13-
int color = 1;
14-
Set<Integer> edges = new HashSet<Integer>();
16+
int color = 1; // Initial color for each node
17+
Set<Integer> edges = new HashSet<Integer>(); // Set of edges representing adjacent nodes
1518
}
1619

20+
/**
21+
* MColoring class solves the M-Coloring problem where the goal is to determine
22+
* if it's possible to color a graph using at most M colors such that no two
23+
* adjacent nodes have the same color.
24+
*/
1725
public final class MColoring {
26+
1827
private MColoring() {
19-
}
20-
static int possiblePaint(ArrayList<Node> nodes, int n, int m) {
28+
} // Prevent instantiation of utility class
2129

22-
// Create a visited array of n nodes
30+
/**
31+
* Determines whether it is possible to color the graph using at most M colors.
32+
*
33+
* @param nodes List of nodes representing the graph.
34+
* @param n The total number of nodes in the graph.
35+
* @param m The maximum number of allowed colors.
36+
* @return true if the graph can be colored using M colors, false otherwise.
37+
*/
38+
static boolean isColoringPossible(ArrayList<Node> nodes, int n, int m) {
39+
40+
// Visited array keeps track of whether each node has been processed.
2341
ArrayList<Integer> visited = new ArrayList<Integer>();
2442
for (int i = 0; i < n + 1; i++) {
25-
visited.add(0);
43+
visited.add(0); // Initialize all nodes as unvisited (0)
2644
}
2745

28-
// maxColors used till now are 1 as
29-
// all nodes are painted color 1
46+
// The number of colors used so far (initially set to 1, since all nodes
47+
// start with color 1).
3048
int maxColors = 1;
3149

50+
// Loop through all the nodes to ensure every node is visited, in case the
51+
// graph is disconnected.
3252
for (int sv = 1; sv <= n; sv++) {
3353
if (visited.get(sv) > 0) {
34-
continue;
54+
continue; // Skip nodes that are already visited
3555
}
3656

37-
// If the starting point is unvisited,
38-
// mark it visited and push it in queue
57+
// If the node is unvisited, mark it as visited and add it to the queue for BFS.
3958
visited.set(sv, 1);
4059
Queue<Integer> q = new LinkedList<>();
4160
q.add(sv);
4261

43-
// BFS
62+
// Perform BFS to process all nodes and their adjacent nodes
4463
while (q.size() != 0) {
45-
int top = q.peek();
64+
int top = q.peek(); // Get the current node from the queue
4665
q.remove();
4766

48-
// Checking all adjacent nodes
49-
// to "top" edge in our queue
67+
// Check all adjacent nodes of the current node
5068
for (int it : nodes.get(top).edges) {
5169

52-
// If the color of the
53-
// adjacent node is same, increase it by
54-
// 1
70+
// If the adjacent node has the same color as the current node, increment its
71+
// color to avoid conflict.
5572
if (nodes.get(top).color == nodes.get(it).color) {
5673
nodes.get(it).color += 1;
5774
}
5875

59-
// If number of colors used exceeds m,
60-
// return 0
76+
// Keep track of the maximum number of colors used so far
6177
maxColors = Math.max(maxColors, Math.max(nodes.get(top).color, nodes.get(it).color));
78+
79+
// If the number of colors used exceeds the allowed limit M, return false.
6280
if (maxColors > m) {
63-
return 0;
81+
return false;
6482
}
6583

66-
// If the adjacent node is not visited,
67-
// mark it visited and push it in queue
84+
// If the adjacent node hasn't been visited yet, mark it as visited and add it
85+
// to the queue for further processing.
6886
if (visited.get(it) == 0) {
6987
visited.set(it, 1);
7088
q.add(it);
7189
}
7290
}
7391
}
7492
}
75-
return 1;
93+
94+
return true; // Possible to color the entire graph with M or fewer colors.
7695
}
7796
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
package com.thealgorithms.datastructures.graphs;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.LinkedList;
6+
import java.util.List;
7+
import java.util.Queue;
8+
9+
/**
10+
* The EdmondsBlossomAlgorithm class implements Edmonds' Blossom Algorithm
11+
* to find the maximum matching in a general graph. The algorithm efficiently
12+
* handles cases where the graph contains odd-length cycles by contracting
13+
* "blossoms" and finding augmenting paths.
14+
*<p>
15+
* <a href="https://stanford.edu/~rezab/classes/cme323/S16/projects_reports/shoemaker_vare.pdf">Documentation of Algorithm (Stanford University)</a>
16+
* <p></p>
17+
* <a href="https://en.wikipedia.org/wiki/Blossom_algorithm">Wikipedia Documentation</a>
18+
*/
19+
public final class EdmondsBlossomAlgorithm {
20+
21+
private EdmondsBlossomAlgorithm() {
22+
}
23+
24+
private static final int UNMATCHED = -1; // Constant to represent unmatched vertices
25+
26+
/**
27+
* Finds the maximum matching in a general graph (Edmonds Blossom Algorithm).
28+
*
29+
* @param edges A list of edges in the graph.
30+
* @param vertexCount The number of vertices in the graph.
31+
* @return A list of matched pairs of vertices.
32+
*/
33+
public static List<int[]> maximumMatching(List<int[]> edges, int vertexCount) {
34+
List<List<Integer>> graph = new ArrayList<>(vertexCount);
35+
36+
// Initialize each vertex's adjacency list.
37+
for (int i = 0; i < vertexCount; i++) {
38+
graph.add(new ArrayList<>());
39+
}
40+
41+
// Populate the graph with the edges
42+
for (int[] edge : edges) {
43+
int u = edge[0];
44+
int v = edge[1];
45+
graph.get(u).add(v);
46+
graph.get(v).add(u);
47+
}
48+
49+
// Initial matching array and auxiliary data structures
50+
int[] match = new int[vertexCount];
51+
Arrays.fill(match, UNMATCHED); // All vertices are initially unmatched
52+
int[] parent = new int[vertexCount];
53+
int[] base = new int[vertexCount];
54+
boolean[] inBlossom = new boolean[vertexCount]; // Indicates if a vertex is part of a blossom
55+
boolean[] inQueue = new boolean[vertexCount]; // Tracks vertices in the BFS queue
56+
57+
// Main logic for finding maximum matching
58+
for (int u = 0; u < vertexCount; u++) {
59+
if (match[u] == UNMATCHED) {
60+
// BFS initialization
61+
Arrays.fill(parent, UNMATCHED);
62+
for (int i = 0; i < vertexCount; i++) {
63+
base[i] = i; // Each vertex is its own base initially
64+
}
65+
Arrays.fill(inBlossom, false);
66+
Arrays.fill(inQueue, false);
67+
68+
Queue<Integer> queue = new LinkedList<>();
69+
queue.add(u);
70+
inQueue[u] = true;
71+
72+
boolean augmentingPathFound = false;
73+
74+
// BFS to find augmenting paths
75+
while (!queue.isEmpty() && !augmentingPathFound) {
76+
int current = queue.poll(); // Use a different name for clarity
77+
for (int y : graph.get(current)) {
78+
// Skip if we are looking at the same edge as the current match
79+
if (match[current] == y) {
80+
continue;
81+
}
82+
83+
if (base[current] == base[y]) {
84+
continue; // Avoid self-loops
85+
}
86+
87+
if (parent[y] == UNMATCHED) {
88+
// Case 1: y is unmatched, we've found an augmenting path
89+
if (match[y] == UNMATCHED) {
90+
parent[y] = current;
91+
augmentingPathFound = true;
92+
updateMatching(match, parent, y); // Augment along this path
93+
break;
94+
}
95+
96+
// Case 2: y is matched, add y's match to the queue
97+
int z = match[y];
98+
parent[y] = current;
99+
parent[z] = y;
100+
if (!inQueue[z]) {
101+
queue.add(z);
102+
inQueue[z] = true;
103+
}
104+
} else {
105+
// Case 3: Both x and y have a parent; check for a cycle/blossom
106+
int baseU = findBase(base, parent, current, y);
107+
if (baseU != UNMATCHED) {
108+
contractBlossom(new BlossomData(new BlossomAuxData(queue, parent, base, inBlossom, match, inQueue), current, y, baseU));
109+
}
110+
}
111+
}
112+
}
113+
}
114+
}
115+
116+
// Create result list of matched pairs
117+
List<int[]> matchingResult = new ArrayList<>();
118+
for (int v = 0; v < vertexCount; v++) {
119+
if (match[v] != UNMATCHED && v < match[v]) {
120+
matchingResult.add(new int[] {v, match[v]});
121+
}
122+
}
123+
124+
return matchingResult;
125+
}
126+
127+
/**
128+
* Updates the matching along the augmenting path found.
129+
*
130+
* @param match The matching array.
131+
* @param parent The parent array used during the BFS.
132+
* @param u The starting node of the augmenting path.
133+
*/
134+
private static void updateMatching(int[] match, int[] parent, int u) {
135+
while (u != UNMATCHED) {
136+
int v = parent[u];
137+
int next = match[v];
138+
match[v] = u;
139+
match[u] = v;
140+
u = next;
141+
}
142+
}
143+
144+
/**
145+
* Finds the base of a node in the blossom.
146+
*
147+
* @param base The base array.
148+
* @param parent The parent array.
149+
* @param u One end of the edge.
150+
* @param v The other end of the edge.
151+
* @return The base of the node or UNMATCHED.
152+
*/
153+
private static int findBase(int[] base, int[] parent, int u, int v) {
154+
boolean[] visited = new boolean[base.length];
155+
156+
// Mark ancestors of u
157+
int currentU = u;
158+
while (true) {
159+
currentU = base[currentU]; // Move assignment out of the condition
160+
visited[currentU] = true;
161+
if (parent[currentU] == UNMATCHED) {
162+
break;
163+
}
164+
currentU = parent[currentU]; // Move assignment out of the condition
165+
}
166+
167+
// Find the common ancestor of v
168+
int currentV = v;
169+
while (true) {
170+
currentV = base[currentV]; // Move assignment out of the condition
171+
if (visited[currentV]) {
172+
return currentV;
173+
}
174+
currentV = parent[currentV]; // Move assignment out of the condition
175+
}
176+
}
177+
178+
/**
179+
* Contracts a blossom and updates the base array.
180+
*
181+
* @param blossomData The data containing the parameters related to the blossom contraction.
182+
*/
183+
private static void contractBlossom(BlossomData blossomData) {
184+
for (int x = blossomData.u; blossomData.auxData.base[x] != blossomData.lca; x = blossomData.auxData.parent[blossomData.auxData.match[x]]) {
185+
int baseX = blossomData.auxData.base[x];
186+
int matchBaseX = blossomData.auxData.base[blossomData.auxData.match[x]];
187+
188+
// Split the inner assignment into two separate assignments
189+
blossomData.auxData.inBlossom[baseX] = true;
190+
blossomData.auxData.inBlossom[matchBaseX] = true;
191+
}
192+
193+
for (int x = blossomData.v; blossomData.auxData.base[x] != blossomData.lca; x = blossomData.auxData.parent[blossomData.auxData.match[x]]) {
194+
int baseX = blossomData.auxData.base[x];
195+
int matchBaseX = blossomData.auxData.base[blossomData.auxData.match[x]];
196+
197+
// Split the inner assignment into two separate assignments
198+
blossomData.auxData.inBlossom[baseX] = true;
199+
blossomData.auxData.inBlossom[matchBaseX] = true;
200+
}
201+
202+
// Update the base for all marked vertices
203+
for (int i = 0; i < blossomData.auxData.base.length; i++) {
204+
if (blossomData.auxData.inBlossom[blossomData.auxData.base[i]]) {
205+
blossomData.auxData.base[i] = blossomData.lca; // Contract to the lowest common ancestor
206+
if (!blossomData.auxData.inQueue[i]) {
207+
blossomData.auxData.queue.add(i); // Add to queue if not already present
208+
blossomData.auxData.inQueue[i] = true;
209+
}
210+
}
211+
}
212+
}
213+
214+
/**
215+
* Auxiliary data class to encapsulate common parameters for the blossom operations.
216+
*/
217+
static class BlossomAuxData {
218+
Queue<Integer> queue; // Queue for BFS traversal
219+
int[] parent; // Parent array to store the paths
220+
int[] base; // Base array to track the base of each vertex
221+
boolean[] inBlossom; // Flags to indicate if a vertex is in a blossom
222+
int[] match; // Array to store matches for each vertex
223+
boolean[] inQueue; // Flags to track vertices in the BFS queue
224+
225+
BlossomAuxData(Queue<Integer> queue, int[] parent, int[] base, boolean[] inBlossom, int[] match, boolean[] inQueue) {
226+
this.queue = queue;
227+
this.parent = parent;
228+
this.base = base;
229+
this.inBlossom = inBlossom;
230+
this.match = match;
231+
this.inQueue = inQueue;
232+
}
233+
}
234+
235+
/**
236+
* BlossomData class with reduced parameters.
237+
*/
238+
static class BlossomData {
239+
BlossomAuxData auxData; // Use the auxiliary data class
240+
int u; // One vertex in the edge
241+
int v; // Another vertex in the edge
242+
int lca; // Lowest Common Ancestor
243+
244+
BlossomData(BlossomAuxData auxData, int u, int v, int lca) {
245+
this.auxData = auxData;
246+
this.u = u;
247+
this.v = v;
248+
this.lca = lca;
249+
}
250+
}
251+
}

0 commit comments

Comments
 (0)