如何在图形中进行反向节点连接?

时间:2012-11-05 11:45:04

标签: java algorithm

我有一个包含4个节点的图表,这些节点与其他节点连接。每个连接都有重量。例如:

  

A - > 5 - >乙

     

A - > 3 - > ç

     

B - > 4 - > ç

     

B - > 3 - > d

每个节点都有相应的反向连接。但是我实现这种后向连接存在问题。这是我现在拥有的算法(单词):

  1. 创建节点(A,B,C,D)
  2. 将节点A连接到节点B
  3. 设置连接权重
  4. 对其他节点重复2,3。
  5. 遵循此算法,我必须分别进行反向连接(节点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
        }
    }
    

2 个答案:

答案 0 :(得分:3)

像这样:

public void connect(Node node, int weight) {
    connections.put(node, weight);
    node.connections.put(this, weight);
}

由于Node用作connections地图中的关键字,因此请不要忘记覆盖其equalshashCode方法。

答案 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);
}