Skip to content

Commit

Permalink
primsAlgorithm.java
Browse files Browse the repository at this point in the history
  • Loading branch information
MSSAYED11 authored and x0lg0n committed Nov 1, 2024
1 parent dbf818f commit e574b7c
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions Java/primsAlgorithm.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import java.util.Arrays;

public class PrimsAlgorithm {
public static void main(String[] args) {
int[][] graph = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
}

static void primMST(int[][] graph) {
int V = graph.length;
int[] parent = new int[V];
int[] key = new int[V];
boolean[] mstSet = new boolean[V];
Arrays.fill(key, Integer.MAX_VALUE);
key[0] = 0;
parent[0] = -1;

for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet, V);
mstSet[u] = true;

for (int v = 0; v < V; v++) {
if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + " \t" + graph[i][parent[i]]);
}

static int minKey(int[] key, boolean[] mstSet, int V) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
}

0 comments on commit e574b7c

Please sign in to comment.