Patryk
Patryk

Reputation: 24092

How to check if DirectedSparsedGraph contains an Edge between Nodes having those 2 nodes?

I am trying to implement creation of kNN graph using jung library. I have came to a moment where I need to check if a link between 2 Nodes already exists in the graph.

My code so far:

for (int i = 0; i < k; i++) {
  for (Iterator<Node> it1 = mGraph.getVertices().iterator(); it1.hasNext();) {
    Node n1 = (Node) it1.next();
    double minDistance = 9999999;
    Node toConnect = null;

    for (Iterator<Node> it2 = mGraph.getVertices().iterator(); it2.hasNext();) {
      Node n2 = (Node) it2.next();
      double currDistance = this.getDistance(n1, n2);
      if( currDistance < minDistance &&  
          mGraph.containsEdge( /* WHAT HERE */ ) ){
        minDistance = currDistance;
        toConnect = n2; 
      }   
    }   
    mGraph.addEdge(new Link(), n1, toConnect, EdgeType.DIRECTED);   
  }           
}

I do not know how to do this since there is only one constructor for Link without any parameters.

Upvotes: 2

Views: 1341

Answers (3)

Joshua O&#39;Madadhain
Joshua O&#39;Madadhain

Reputation: 2704

isNeighbor() works for undirected graphs or if you don't care how the two nodes are connected (that is, which way the existing edge, if any, goes) . For a directed Graph you probably want isPredecessor().

Upvotes: 1

Patryk
Patryk

Reputation: 24092

I have found out that I can do this the following way (maybe someone will comment if it's efficient and ok)

mGraph.isNeighbor(n1, n2)

Upvotes: 1

DCarochoC
DCarochoC

Reputation: 76

For example if you have two nodes, n1 and n2, and your graph is called mGraph you can simply create a new method:

public boolean existsLink(Node n1, Node n2) {
  return mGraph.getNeighbors(n1).contains(n2);
}

If it returns true, it means the edge exists; returns false if the edge does not exist. Please note that mGraph.getNeighbors(n1) is a Collection.

You could also use the method: mGraph.containsEdge(E edge). But I don't know wich type is your E edge, and which methods it has.

Upvotes: 0

Related Questions