I’m developing an adjacency matrix so i can try and use a DFS to solve the euler circuit problem.
This is the relevant code to my question:
public class Graph {
private int numVertex;
private int numEdges;
private boolean[][] adj;
public Graph(int numVertex, int numEdges) {
this.numVertex = numVertex;
this.numEdges = numEdges;
this.adj = new boolean[numVertex][numVertex];
}
public void addEdge(int start, int end){
if(!adj[start][end])
numEdges++;
adj[start][end] = true;
adj[end][start] = true;
}
When i try and test run this code by adding some edges i get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Graph.addEdge(Graph.java:18)
at Graph.main(Graph.java:66)
I’m using this to test the code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numVertices = input.nextInt();
int numLinks = input.nextInt();
int startNode = input.nextInt();
Graph g = new Graph(numVertices, numLinks);
for(int i = 0; i<numLinks; i++){
g.addEdge(input.nextInt(),input.nextInt());
}
I think the problem is in the addEdge function. What am i doing wrong?
Remember that your matrix is zero-based.
If you passed 4 as numVertices, your matrix will go from 0,0 to 3,3.
Then if you try to add an edge between vertex 4 and any other you will have an error…