|
| 1 | +package com.thealgorithms.datastructures.graphs; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public final class MultistageGraph { |
| 7 | + |
| 8 | + private MultistageGraph() { |
| 9 | + |
| 10 | + } |
| 11 | + private int k; // number of partitions (k > 2) |
| 12 | + |
| 13 | + // Adjacency list to store edges between different stages |
| 14 | + public List<List<Integer>> adjacencyList; |
| 15 | + |
| 16 | + public MultistageGraph(int k) { |
| 17 | + this.k = k; |
| 18 | + this.adjacencyList = new ArrayList<>(); |
| 19 | + |
| 20 | + // Initialize the adjacency list with empty lists for each stage |
| 21 | + for (int i = 0; i < k; i++) { |
| 22 | + adjacencyList.add(new ArrayList<>()); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public void addEdge(int fromStage, int toStage) throws IllegalArgumentException { |
| 27 | + if (!isValidStageNumber(fromStage)) { |
| 28 | + throw new IllegalArgumentException("Invalid stage number: " + fromStage); |
| 29 | + } |
| 30 | + |
| 31 | + if (!isValidStageNumber(toStage)) { |
| 32 | + throw new IllegalArgumentException("Invalid stage number: " + toStage); |
| 33 | + } |
| 34 | + |
| 35 | + // Check if the edge exists between the given stages, and add it if not |
| 36 | + if (adjacencyList.get(fromStage - 1).contains(toStage)) { |
| 37 | + System.out.println("Edge already exists between stage " + fromStage + " and stage " + toStage); |
| 38 | + } else { |
| 39 | + adjacencyList.get(fromStage - 1).add(toStage); |
| 40 | + System.out.println("Added edge between stage " + fromStage + " and stage " + toStage); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + private boolean isValidStageNumber(int stage) { |
| 45 | + return (stage >= 1 && stage <= k); |
| 46 | + } |
| 47 | + |
| 48 | + public void printGraph() { |
| 49 | + System.out.println("Multistage Graph:"); |
| 50 | + |
| 51 | + for (int i = 0; i < k; i++) { |
| 52 | + System.out.print(i + " -> "); |
| 53 | + |
| 54 | + for (Integer adjacentStage : adjacencyList.get(i)) { |
| 55 | + if (!adjacentStage.equals(i)) { |
| 56 | + System.out.println(" -> " + adjacentStage); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + public static void main(String[] args) { |
| 63 | + MultistageGraph graph = new MultistageGraph(4); // Create a multistage graph with k = 4 partitions |
| 64 | + |
| 65 | + try { |
| 66 | + graph.addEdge(1, 2); |
| 67 | + graph.addEdge(1, 3); |
| 68 | + graph.addEdge(2, 3); |
| 69 | + graph.printGraph(); |
| 70 | + } catch (IllegalArgumentException e) { |
| 71 | + System.out.println("Error: " + e.getMessage()); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments