Skip to content

Commit b106dc3

Browse files
Merge branch 'master' into master
2 parents b2bf70b + f8f315e commit b106dc3

File tree

7 files changed

+590
-1
lines changed

7 files changed

+590
-1
lines changed

src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,15 @@ private BitSwap() {
1717
* @return The modified value with swapped bits
1818
* @throws IllegalArgumentException if either position is negative or ≥ 32
1919
*/
20+
2021
public static int bitSwap(int data, final int posA, final int posB) {
2122
if (posA < 0 || posA >= Integer.SIZE || posB < 0 || posB >= Integer.SIZE) {
2223
throw new IllegalArgumentException("Bit positions must be between 0 and 31");
2324
}
2425

25-
if (SingleBitOperations.getBit(data, posA) != SingleBitOperations.getBit(data, posB)) {
26+
boolean bitA = ((data >> posA) & 1) != 0;
27+
boolean bitB = ((data >> posB) & 1) != 0;
28+
if (bitA != bitB) {
2629
data ^= (1 << posA) ^ (1 << posB);
2730
}
2831
return data;
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
package com.thealgorithms.datastructures.lists;
2+
3+
/**
4+
* This class is a circular doubly linked list implementation. In a circular
5+
* doubly linked list,
6+
* the last node points back to the first node and the first node points back to
7+
* the last node,
8+
* creating a circular chain in both directions.
9+
*
10+
* This implementation includes basic operations such as appending elements to
11+
* the end,
12+
* removing elements from a specified position, and converting the list to a
13+
* string representation.
14+
*
15+
* @param <E> the type of elements held in this list
16+
*/
17+
public class CircularDoublyLinkedList<E> {
18+
static final class Node<E> {
19+
Node<E> next;
20+
Node<E> prev;
21+
E value;
22+
23+
private Node(E value, Node<E> next, Node<E> prev) {
24+
this.value = value;
25+
this.next = next;
26+
this.prev = prev;
27+
}
28+
}
29+
30+
private int size;
31+
Node<E> head = null;
32+
33+
/**
34+
* Initializes a new circular doubly linked list. A dummy head node is used for
35+
* simplicity,
36+
* pointing initially to itself to ensure the list is never empty.
37+
*/
38+
public CircularDoublyLinkedList() {
39+
head = new Node<>(null, null, null);
40+
head.next = head;
41+
head.prev = head;
42+
size = 0;
43+
}
44+
45+
/**
46+
* Returns the current size of the list.
47+
*
48+
* @return the number of elements in the list
49+
*/
50+
public int getSize() {
51+
return size;
52+
}
53+
54+
/**
55+
* Appends a new element to the end of the list. Throws a NullPointerException
56+
* if
57+
* a null value is provided.
58+
*
59+
* @param value the value to append to the list
60+
* @throws NullPointerException if the value is null
61+
*/
62+
public void append(E value) {
63+
if (value == null) {
64+
throw new NullPointerException("Cannot add null element to the list");
65+
}
66+
Node<E> newNode = new Node<>(value, head, head.prev);
67+
head.prev.next = newNode;
68+
head.prev = newNode;
69+
size++;
70+
}
71+
72+
/**
73+
* Returns a string representation of the list in the format "[ element1,
74+
* element2, ... ]".
75+
* An empty list is represented as "[]".
76+
*
77+
* @return the string representation of the list
78+
*/
79+
public String toString() {
80+
if (size == 0) {
81+
return "[]";
82+
}
83+
StringBuilder sb = new StringBuilder("[ ");
84+
Node<E> current = head.next;
85+
while (current != head) {
86+
sb.append(current.value);
87+
if (current.next != head) {
88+
sb.append(", ");
89+
}
90+
current = current.next;
91+
}
92+
sb.append(" ]");
93+
return sb.toString();
94+
}
95+
96+
/**
97+
* Removes and returns the element at the specified position in the list.
98+
* Throws an IndexOutOfBoundsException if the position is invalid.
99+
*
100+
* @param pos the position of the element to remove
101+
* @return the value of the removed element - pop operation
102+
* @throws IndexOutOfBoundsException if the position is out of range
103+
*/
104+
public E remove(int pos) {
105+
if (pos >= size || pos < 0) {
106+
throw new IndexOutOfBoundsException("Position out of bounds");
107+
}
108+
Node<E> current = head.next;
109+
for (int i = 0; i < pos; i++) {
110+
current = current.next;
111+
}
112+
current.prev.next = current.next;
113+
current.next.prev = current.prev;
114+
E removedValue = current.value;
115+
size--;
116+
return removedValue;
117+
}
118+
}
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
package com.thealgorithms.graph;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashSet;
5+
import java.util.List;
6+
import java.util.Set;
7+
8+
/**
9+
* Implementation of the Bron–Kerbosch algorithm with pivoting for enumerating all maximal cliques
10+
* in an undirected graph.
11+
*
12+
* <p>The input graph is represented as an adjacency list where {@code adjacency.get(u)} returns the
13+
* set of vertices adjacent to {@code u}. The algorithm runs in time proportional to the number of
14+
* maximal cliques produced and is widely used for clique enumeration problems.</p>
15+
*
16+
* @author <a href="https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm">Wikipedia: Bron–Kerbosch algorithm</a>
17+
*/
18+
public final class BronKerbosch {
19+
20+
private BronKerbosch() {
21+
}
22+
23+
/**
24+
* Finds all maximal cliques of the provided graph.
25+
*
26+
* @param adjacency adjacency list where {@code adjacency.size()} equals the number of vertices
27+
* @return a list containing every maximal clique, each represented as a {@link Set} of vertices
28+
* @throws IllegalArgumentException if the adjacency list is {@code null}, contains {@code null}
29+
* entries, or references invalid vertices
30+
*/
31+
public static List<Set<Integer>> findMaximalCliques(List<Set<Integer>> adjacency) {
32+
if (adjacency == null) {
33+
throw new IllegalArgumentException("Adjacency list must not be null");
34+
}
35+
36+
int n = adjacency.size();
37+
List<Set<Integer>> graph = new ArrayList<>(n);
38+
for (int u = 0; u < n; u++) {
39+
Set<Integer> neighbors = adjacency.get(u);
40+
if (neighbors == null) {
41+
throw new IllegalArgumentException("Adjacency list must not contain null sets");
42+
}
43+
Set<Integer> copy = new HashSet<>();
44+
for (int v : neighbors) {
45+
if (v < 0 || v >= n) {
46+
throw new IllegalArgumentException("Neighbor index out of bounds: " + v);
47+
}
48+
if (v != u) {
49+
copy.add(v);
50+
}
51+
}
52+
graph.add(copy);
53+
}
54+
55+
Set<Integer> r = new HashSet<>();
56+
Set<Integer> p = new HashSet<>();
57+
Set<Integer> x = new HashSet<>();
58+
for (int v = 0; v < n; v++) {
59+
p.add(v);
60+
}
61+
62+
List<Set<Integer>> cliques = new ArrayList<>();
63+
bronKerboschPivot(r, p, x, graph, cliques);
64+
return cliques;
65+
}
66+
67+
private static void bronKerboschPivot(Set<Integer> r, Set<Integer> p, Set<Integer> x, List<Set<Integer>> graph, List<Set<Integer>> cliques) {
68+
if (p.isEmpty() && x.isEmpty()) {
69+
cliques.add(new HashSet<>(r));
70+
return;
71+
}
72+
73+
int pivot = choosePivot(p, x, graph);
74+
Set<Integer> candidates = new HashSet<>(p);
75+
if (pivot != -1) {
76+
candidates.removeAll(graph.get(pivot));
77+
}
78+
79+
for (Integer v : candidates) {
80+
r.add(v);
81+
Set<Integer> newP = intersection(p, graph.get(v));
82+
Set<Integer> newX = intersection(x, graph.get(v));
83+
bronKerboschPivot(r, newP, newX, graph, cliques);
84+
r.remove(v);
85+
p.remove(v);
86+
x.add(v);
87+
}
88+
}
89+
90+
private static int choosePivot(Set<Integer> p, Set<Integer> x, List<Set<Integer>> graph) {
91+
int pivot = -1;
92+
int maxDegree = -1;
93+
Set<Integer> union = new HashSet<>(p);
94+
union.addAll(x);
95+
for (Integer v : union) {
96+
int degree = graph.get(v).size();
97+
if (degree > maxDegree) {
98+
maxDegree = degree;
99+
pivot = v;
100+
}
101+
}
102+
return pivot;
103+
}
104+
105+
private static Set<Integer> intersection(Set<Integer> base, Set<Integer> neighbors) {
106+
Set<Integer> result = new HashSet<>();
107+
for (Integer v : base) {
108+
if (neighbors.contains(v)) {
109+
result.add(v);
110+
}
111+
}
112+
return result;
113+
}
114+
}
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package com.thealgorithms.graph;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Arrays;
5+
import java.util.Queue;
6+
7+
/**
8+
* Implementation of the Edmonds–Karp algorithm for computing the maximum flow of a directed graph.
9+
* <p>
10+
* The algorithm runs in O(V * E^2) time and is a specific implementation of the Ford–Fulkerson
11+
* method where the augmenting paths are found using breadth-first search (BFS) to ensure the
12+
* shortest augmenting paths (in terms of the number of edges) are used.
13+
* </p>
14+
*
15+
* <p>The graph is represented with a capacity matrix where {@code capacity[u][v]} denotes the
16+
* capacity of the edge from {@code u} to {@code v}. Negative capacities are not allowed.</p>
17+
*
18+
* @author <a href="https://en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm">Wikipedia: EdmondsKarp algorithm</a>
19+
*/
20+
public final class EdmondsKarp {
21+
22+
private EdmondsKarp() {
23+
}
24+
25+
/**
26+
* Computes the maximum flow from {@code source} to {@code sink} in the provided capacity matrix.
27+
*
28+
* @param capacity the capacity matrix representing the directed graph; must be square and non-null
29+
* @param source the source vertex index
30+
* @param sink the sink vertex index
31+
* @return the value of the maximum flow between {@code source} and {@code sink}
32+
* @throws IllegalArgumentException if the matrix is {@code null}, not square, contains negative
33+
* capacities, or if {@code source} / {@code sink} indices are invalid
34+
*/
35+
public static int maxFlow(int[][] capacity, int source, int sink) {
36+
if (capacity == null || capacity.length == 0) {
37+
throw new IllegalArgumentException("Capacity matrix must not be null or empty");
38+
}
39+
40+
final int n = capacity.length;
41+
for (int row = 0; row < n; row++) {
42+
if (capacity[row] == null || capacity[row].length != n) {
43+
throw new IllegalArgumentException("Capacity matrix must be square");
44+
}
45+
for (int col = 0; col < n; col++) {
46+
if (capacity[row][col] < 0) {
47+
throw new IllegalArgumentException("Capacities must be non-negative");
48+
}
49+
}
50+
}
51+
52+
if (source < 0 || source >= n || sink < 0 || sink >= n) {
53+
throw new IllegalArgumentException("Source and sink must be valid vertex indices");
54+
}
55+
if (source == sink) {
56+
return 0;
57+
}
58+
59+
final int[][] residual = new int[n][n];
60+
for (int i = 0; i < n; i++) {
61+
residual[i] = Arrays.copyOf(capacity[i], n);
62+
}
63+
64+
final int[] parent = new int[n];
65+
int maxFlow = 0;
66+
67+
while (bfs(residual, source, sink, parent)) {
68+
int pathFlow = Integer.MAX_VALUE;
69+
for (int v = sink; v != source; v = parent[v]) {
70+
int u = parent[v];
71+
pathFlow = Math.min(pathFlow, residual[u][v]);
72+
}
73+
74+
for (int v = sink; v != source; v = parent[v]) {
75+
int u = parent[v];
76+
residual[u][v] -= pathFlow;
77+
residual[v][u] += pathFlow;
78+
}
79+
80+
maxFlow += pathFlow;
81+
}
82+
83+
return maxFlow;
84+
}
85+
86+
private static boolean bfs(int[][] residual, int source, int sink, int[] parent) {
87+
Arrays.fill(parent, -1);
88+
parent[source] = source;
89+
90+
Queue<Integer> queue = new ArrayDeque<>();
91+
queue.add(source);
92+
93+
while (!queue.isEmpty()) {
94+
int u = queue.poll();
95+
for (int v = 0; v < residual.length; v++) {
96+
if (residual[u][v] > 0 && parent[v] == -1) {
97+
parent[v] = u;
98+
if (v == sink) {
99+
return true;
100+
}
101+
queue.add(v);
102+
}
103+
}
104+
}
105+
return false;
106+
}
107+
}

0 commit comments

Comments
 (0)