public class Solution {
public static void main(String[] args) throws Exception { //have this return the result of DFS
Scanner input = new Scanner(System.in);
int vertices = input.nextInt();
Graph mygraph = new Graph (vertices);
int edges = input.nextInt();
//set up input as edges
while (input.hasNextInt()) {
int from = input.nextInt() - 1;
int to = input.nextInt() - 1;
//add the reciprocating vertex neighbors
mygraph.nodes[from].addNeighbor(mygraph.nodes[to]);//null pointer here
mygraph.nodes[to].addNeighbor(mygraph.nodes[from]);
}
}
}
class Graph {
int size;
Vertex[] nodes;
Graph(int size) {
this.size = size;
this.nodes = new Vertex[size];
}
}
class Vertex {
int value;
Vertex[] neighbors;
int available;
Vertex(int value) {
this.value = value;
this.neighbors = new Vertex[50];
this.available = 0;
}
//add to the neighbors list of this array
void addNeighbor(Vertex v) {
this.neighbors[this.available] = v;
this.available = this.available + 1;
}
}
not sure as to why I'm getting a null pointer here? To my understanding, null pointers are when something is not getting initialized properly--any guidance?
What I'm trying to do is add the neighbors of vertices to one another as they come up in the input. One possible issue is that in the Vertex class I'm initializing the size of the Vertex array as size, but I don't see any other way to accurately get the size of the array.
I haven't seen any other problem online like this one, hence why Im asking!