Skip to content

Instantly share code, notes, and snippets.

@ZacharyJacobCollins
Last active November 30, 2016 19:34
Show Gist options
  • Save ZacharyJacobCollins/afc89cf2a811d8472adeb2b67a5083b1 to your computer and use it in GitHub Desktop.
Save ZacharyJacobCollins/afc89cf2a811d8472adeb2b67a5083b1 to your computer and use it in GitHub Desktop.
Warshall's algorithm
/**
* Zachary Collins
* Lab 2
* 314
*/
import java.util.Scanner;
/** Class Warshall **/
public class Warshall
{
private int V;
private boolean[][] tc;
/** Function to make the transitive closure **/
public void getTC(int[][] graph, Warshall w) {
w.printClosure();
this.V = graph.length;
tc = new boolean[V][V];
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (graph[i][j] != 0)
tc[i][j] = true;
}
tc[i][i] = true;
}
w.printClosure();
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (tc[j][i])
for (int k = 0; k < V; k++)
if (tc[j][i] && tc[i][k])
tc[j][k] = true;
}
}
w.printClosure();
}
/** Function to print the transitive closure **/
public void printClosure()
{
System.out.println("\nTransitive closure :\n");
System.out.print(" ");
for (int v = 0; v < V; v++) {
System.out.print(" " + v );
}
System.out.println();
for (int v = 0; v < V; v++) {
System.out.print(v +" ");
for (int w = 0; w < V; w++) {
if (tc[v][w]) {
System.out.print(" 1 ");
}
else {
System.out.print(" 0 ");
}
}
System.out.println();
}
}
public void printGraph(int[][] graph) {
int L = graph.length;
//Create top labels for printing
String topLabel = " ";
for (int k=1; k <= L; k++) {
topLabel += k+" ";
}
System.out.println(topLabel);
for (int i = 0; i < L; i++) {
//Print out vertical labels for printing matrix
System.out.print(" "+(i+1)+" ");
for (int j = 0; j < L; j++) {
System.out.print(" "+graph[i][j]+" ");
}
System.out.println();
}
}
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Warshall Algorithm Test\n");
Warshall w = new Warshall();
/** Accept number of vertices **/
System.out.println("How many vertices\n");
int V = scan.nextInt();
/** get graph **/
System.out.println("\nEnter matrix\n");
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = scan.nextInt();
w.printGraph(graph);
// w.getTC(graph, w);
// w.printClosure();
}
}
//Input
//
//0 1 0 1 1
//1 0 1 0 0
//1 0 1 1 0
//1 0 0 0 1
//1 0 1 0 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment