I have a graph with 4 nodes which are connected with other nodes. Each connection has weight. For example:
A -> 5 -> B
A -> 3 -> C
B -> 4 -> C
B -> 3 -> D
Each node has backward connection correspondingly. But I have a problem with realization of such backward connection. Here is algorithm (in words) of what I have now:
- Create nodes (A, B, C, D)
- Connect node A to node B
- Set connection weight
- Repeat 2,3 for other nodes.
Following this algorithm I have to make backward connections (node B to node A) separately. And if I have 100 nodes or more, it’ll be a trial for my attention.
How to make these backward connections during connection creation?
Here is a Node class:
public class Node {
private String name;
private Map<Node, Integer> connections;
public Node(String name) {
this.name = name;
connections = new HashMap<Node, Integer>();
}
public void connect(Node node, int weight) {
connections.put(node, weight);
//It is expected to make backward connection here
}
}
Like this:
Since
Nodeis used as the key in theconnectionsmap, don’t forget to override itsequalsandhashCodemethods.