我有一个包含4个节点的图表,这些节点与其他节点连接。每个连接都有重量。例如:
A - > 5 - >乙
A - > 3 - > ç
B - > 4 - > ç
B - > 3 - > d
每个节点都有相应的反向连接。但是我实现这种后向连接存在问题。这是我现在拥有的算法(单词):
遵循此算法,我必须分别进行反向连接(节点B到节点A)。如果我有100个节点或更多节点,这将是我的注意力的试验。
如何在连接创建期间进行这些反向连接?
这是一个Node类:
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
}
}
答案 0 :(得分:3)
像这样:
public void connect(Node node, int weight) {
connections.put(node, weight);
node.connections.put(this, weight);
}
由于Node
用作connections
地图中的关键字,因此请不要忘记覆盖其equals
和hashCode
方法。
答案 1 :(得分:2)
您可以使用:
node.getConnections().put(this, weight);
但是,我会建议改变设计:
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);
}