Reputation: 2481
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:
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
}
}
Upvotes: 2
Views: 204
Reputation: 13872
You can use:
node.getConnections().put(this, weight);
But, i'll recommend a design change:
class Node
{
String name;
List<Node> connectedNodes;
}
class Branch
{
Node a;
Node b;
int weight;
}
// calling part of program
// initizaliztion of fields already done
public void connect(Node node1, Node node2, int weight)
{
// checks required:
// if a branch already exists
node1.connectedNodes.Add(node2);
node2.connectedNodes.Add(node1);
Branch branch = new Branch(node1, node2, weight);
}
Upvotes: 2
Reputation: 726599
Like this:
public void connect(Node node, int weight) {
connections.put(node, weight);
node.connections.put(this, weight);
}
Since Node
is used as the key in the connections
map, don't forget to override its equals
and hashCode
methods.
Upvotes: 3