-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxFlowMinCut.java
More file actions
103 lines (80 loc) · 2.84 KB
/
MaxFlowMinCut.java
File metadata and controls
103 lines (80 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.mycompany.algorithm_final_project;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;
/**
*
* @author israkkayumchowdhury
*/
class Graph {
private int vertices;
private int[][] residualGraph;
public Graph(int vertices) {
this.vertices = vertices;
residualGraph = new int[vertices+1][vertices+1];
}
public void addEdge(int source, int destination, int capacity) {
residualGraph[source][destination] = capacity;
}
public int maxFlow(int source, int sink) {
int[] parent = new int[vertices];
int maxFlow = 0;
while (bfs(source, sink, parent)) {
int pathFlow = Integer.MAX_VALUE;
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
pathFlow = Math.min(pathFlow, residualGraph[u][v]);
}
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
residualGraph[u][v] -= pathFlow;
residualGraph[v][u] += pathFlow;
}
maxFlow += pathFlow;
}
return maxFlow;
}
private boolean bfs(int source, int sink, int[] parent) {
boolean[] visited = new boolean[vertices];
Arrays.fill(visited, false);
Queue<Integer> queue = new ArrayDeque<>();
queue.add(source);
visited[source] = true;
parent[source] = -1;
while (!queue.isEmpty()) {
int u = queue.poll();
for (int v = 0; v < vertices; v++) {
if (!visited[v] && residualGraph[u][v] > 0) {
queue.add(v);
parent[v] = u;
visited[v] = true;
}
}
}
return visited[sink];
}
}
public class MaxFlowMinCut {
public void main_func() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of vertices in the graph: ");
int vertices = scanner.nextInt();
Graph graph = new Graph(vertices);
System.out.print("Enter the number of edges: ");
int edges = scanner.nextInt();
for (int i = 0; i < edges; i++) {
System.out.println("Enter edge " + (i + 1) + " details (source destination capacity): ");
int source = scanner.nextInt();
int destination = scanner.nextInt();
int capacity = scanner.nextInt();
graph.addEdge(source, destination, capacity);
}
System.out.print("Enter the source vertex: ");
int source = scanner.nextInt();
System.out.print("Enter the sink vertex: ");
int sink = scanner.nextInt();
int maxFlow = graph.maxFlow(source, sink);
System.out.println("The maximum flow in the graph is: " + maxFlow);
}
}