0% found this document useful (0 votes)
9 views8 pages

NP Assignment - 2

Uploaded by

agkumar10514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views8 pages

NP Assignment - 2

Uploaded by

agkumar10514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

2.
import java.util.Scanner;

public class SPT {


private int V;
private char[] vertices;

SPT(int verticesCount) {
V = verticesCount;
vertices = new char[V];
}

int minDistance(int dist[], Boolean sptSet[]) {


int min = Integer.MAX_VALUE;
int min_index = -1;
for (int v = 0; v < V; v++) {
if (sptSet[v] == false && dist[v] < min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}

void dijkstraSPT(int graph[][], char[] vertexNames) {


vertices = vertexNames;
int[] distance = new int[V];
int[] parent = new int[V];
Boolean sptSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
distance[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}
distance[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(distance, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] != 0 && distance[u] !=
Integer.MAX_VALUE &&
distance[u] + graph[u][v] < distance[v]) {
parent[v] = u;
distance[v] = distance[u] + graph[u][v];
}
}
}
printSPT(parent, distance);
}

void printSPT(int parent[], int distance[]) {


System.out.println("Shortest Path Tree (SPT) from the start
vertex:");
System.out.println("Edge \tDistance");
for (int i = 1; i < V; i++) {
System.out.println(vertices[parent[i]] + " - " + vertices[i] +
"\t" + distance[i]);
}
}

public static void main(String[] args) {


SPT spt = new SPT(4);

char[] vertexNames = {'a', 'b', 'c', 'd'};


int[][] adj = {
{0, 6, 6, 6},
{6, 0, 0, 2},
{6, 0, 0, 2},
{6, 2, 2, 0}
};

spt.dijkstraSPT(adj, vertexNames);
}
}
3.

You might also like