Is there a way to handle Lists in Java as twodimensional?
The situation: I have a graph with nodes, edges and weight per edge. Now I need a data structure to store for each node: a) its neighbours b) the edge's weight for each neigbour
First I thought of creating a new class "node" with an identifyer and something like a two-dimensional array to store neighbour-identifyers and edge-weights. But the number of neighbours for each node is not given and may increase dynamically during runtime. Therefore I think two-dimensional arrays are not the way to go here.
I thought it would be possible to have in the class "node" a list like:
List<node> neighbours = new ArrayList<node>();
But obviously this only handles the neighbour nodes - not the weights of their edges.
Does anybody have a hint how to construct such a "graph" where for every node the neighbour's identifyers and the corresponding edge weight are stored?
Thank you for reading :-)
Most straight-forward is to use HashMap
:
class Edge {
// represents edge with destination node and it's weight
private final Node node;
private final int weight;
Edge(Node node, int weight) {
this.node = node;
this.weight = weight;
}
}
// represents map which holds all outgoing edges keyed by source nodes.
Map<Node, Set<Edges>> edgesByOutgoingNodes = new HashMap<Node, Set<Edges>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With