/**
* Tugas : Graph Adjacency Matrices
*
* Rafael Asi Kristanto Tambunan
* 5025201168
* Teknik Informatika
*/
class Graph {
private int numOfNodes;
private boolean directed;
private boolean weighted;
private float[][] matrix;
private boolean[][] isVisited;
public Graph(int numOfNodes, boolean directed, boolean weighted) {
this.directed = directed;
this.weighted = weighted;
this.numOfNodes = numOfNodes;
matrix = new float[numOfNodes][numOfNodes];
isVisited = new boolean[numOfNodes][numOfNodes];
}
public void addEdge(int source, int destination, float weight) {
float valueToAdd = weight;
if (!weighted) {
valueToAdd = 1;
}
matrix[source][destination] = valueToAdd;
isVisited[source][destination] = true;
if (!directed) {
matrix[destination][source] = valueToAdd;
isVisited[destination][source] = true;
}
}
public void printMatrix() {
for (int i = 0; i < numOfNodes; i++) {
for (int j = 0; j < numOfNodes; j++) {
if (isVisited[i][j])
System.out.format("%8s", String.valueOf(matrix[i][j]));
else System.out.format("%8s", "/ ");
}
System.out.println();
}
}
public void printEdges() {
for (int i = 0; i < numOfNodes; i++) {
System.out.print("Node " + i + " is connected to: ");
for (int j = 0; j < numOfNodes; j++) {
if (isVisited[i][j]) {
System.out.print(j + " ");
}
}
System.out.println();
}
}
public boolean hasEdge(int source, int destination) {
return isVisited[source][destination];
}
public Float getEdgeValue(int source, int destination) {
if (!weighted || !isVisited[source][destination])
return null;
return matrix[source][destination];
}
}
public class AdjacencyMatrices {
public static void main(String[] args) {
Graph graph = new Graph(5, false, true);
graph.addEdge(0, 1, 7);
graph.addEdge(0, 2, 14);
graph.addEdge(0, 3, 5);
graph.addEdge(1, 0, 13);
graph.addEdge(1, 2, 4);
graph.addEdge(1, 3, -5);
graph.addEdge(1, 4, 6);
graph.addEdge(2, 3, 3);
graph.addEdge(2, 4, 8);
graph.addEdge(3, 2, 12);
graph.addEdge(3, 3, 0);
System.out.println("The Matrix :");
graph.printMatrix();
System.out.println();
System.out.println();
System.out.println("Connected Node : ");
graph.printEdges();
System.out.println();
System.out.println("Does an edge from 1 to 0 exist?");
if (graph.hasEdge(0,1)) {
System.out.println("Yes");
}
else System.out.println("No");
}
}