public class AdjacencyMatrix {
private String [] nodes;
private int [][] matrix;
public AdjacencyMatrix(String [] nodes,int [][] matrix){
this.nodes = nodes;
this.matrix = matrix;
}
boolean isSymmetric(){
boolean sym = true;
for(int i=0;i<matrix.length;i++){
for(int j=i+1; j < matrix[0].length ; j++){
if (matrix[i][j] != matrix[j][i]){
sym = false;
break;
}
}
}
return sym;
}
public Graph createGraph(){
Graph graph = new Graph();
Node[] NODES = new Node[nodes.length];
for (int i=0; i<nodes.length; i++){
NODES[i] = new Node(nodes[i]);
graph.addNode(NODES[i]);
}
for(int i=0;i<matrix.length;i++){
for(int j=i;j<matrix[0].length;j++){
int distance = matrix[i][j];
if (distance != 0){
graph.addEdge(new Edge(NODES[i], NODES[j], distance));
}
}
}
return graph;
}
public long pathLength(int[] path){
long sum = 0;
for (int i=0; i<path.length - 1; i++){
if (matrix[path[i]][path[i+1]] != 0)
sum += matrix[path[i]][path[i+1]];
else {
sum = 0;
break;
}
}
return sum;
}
public static void main(String[] args){
String[] nodes = {"A", "B", "C", "D", "E"};
int [][] matrix= { {0, 2, 2, 1, 0},
{2, 0, 1, 0, 0},
{2, 1, 0, 0, 1},
{1, 0, 0, 0, 4},
{0, 0, 1, 4, 7}};
AdjacencyMatrix am = new AdjacencyMatrix(nodes, matrix);
Graph graph = am.createGraph();
int[] a = {0, 2, 4, 4, 3, 0};
int[] b = {0, 1, 2, 4, 4, 3, 0};
graph.writeGraph();
am.pathLength(a);
am.pathLength(b);
}
}