/* * Since matrices for directed graphs are symmetrical, we have to add * [destination][source] at the same time as [source][destination] */ if (!directed) { matrix[destination][source] = valueToAdd; isSetMatrix[destination][source] = true; }
}
publicvoidaddEdge(int source, int destination, float weight){ float valueToAdd = weight; if (!weighted) { valueToAdd = 1; }
/* * Since matrices for directed graphs are symmetrical, we have to add * [destination][source] at the same time as [source][destination] */ if (!directed) { matrix[destination][source] = valueToAdd; isSetMatrix[destination][source] = true; }
}
publicvoidprintMatrix(){ for (int i = 0; i < numOfNodes; i++) { for (int j = 0; j < numOfNodes; j++) { if (isSetMatrix[i][j]) { System.out.format("%8s", String.valueOf(matrix[i][j])); } else { System.out.format("%8s", "/ "); } } System.out.println(); } }
publicvoidprintEdges(){ for (int i = 0; i < numOfNodes; i++) { System.out.print("Node " + i + " is connected to: "); for (int j = 0; j < numOfNodes; j++) { if (isSetMatrix[i][j]) { System.out.print(j + " "); } } System.out.println(); } }
publicbooleanhasEdge(int source, int destination){ return isSetMatrix[source][destination]; }
public Float getEdgeValue(int source, int destination){ if (!weighted || !isSetMatrix[source][destination]) { returnnull; } return matrix[source][destination]; }
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"); } } }
Graph graph = new Graph(true); Node a = new Node(0, "A"); Node b = new Node(1, "B"); Node c = new Node(2, "C"); Node d = new Node(3, "D"); Node e = new Node(4, "E");
Adjacency matrices have a much faster look-up time than adjacency lists. For example, if we wanted to check whether node 0 has an edge leading to node 4 we could just check the matrix at indices [0,4] which gives us constant execution time.
Adding edges is also much faster in adjacency matrices - simply change the value at position [i,j] to add an edge from node i to node j, while with lists (if we don't have access to the pointer to the last element) can also take O(n) time, especially if we need to check whether that edge already exists in the list or not.
As far as space is concerned - djacency lists are much more efficient
Checking whether an edge is part of a graph: adjacency matrix, since checking whether an edge is part of a graph takes O(1) time, while in adjacency lists it takes O(lengthOfList) time
Adding or removing edges from the graph: adjacency matrix, same difference as in the previous case
Traversing the graph: adjacency list, takes O(N + E) time instead of O(N^2)