Patric
Patric

Reputation: 57

Directed graph and undirected graph - Java

I'm implementing some algorithms to teach myself about graphs and how to work with them. What would you recommend is the best way to do that in Java?

I just wanted to ask u if u can give just a short help with a short very simply class definition for directed graph and weighted directed graph?

I looked over the web but i do not want an implementation of it, just a short definition of the classes....what u think is the best data structure to use ? Adjacent Lists?

For an undirected Graph i defined it as follow:

public interface Graph { 
  Collection vertices();  // returns a collection of all the 
        //   Vertex objects in the graph 
  Collection edges();  // returns a collection of all the 
     //   Edge objects in the graph 
  Collection incidentEdges(Vertex v); // returns a collection of  
       //   Edges incident to v 
  boolean isAdjacent(Vertex v, Vertex w); // return true if v and     
}                 //   w are adjacent 

public class Vertex { 
  public boolean visited;  // initially false for all vertices 
} 

public class Edge { 
  Vertex v1, v2;     // undirected edge 
  Vertex opposite(Vertex v); // given a vertex return the one 
}          // at the other end of this edge 

Upvotes: 1

Views: 6324

Answers (2)

AkiRoss
AkiRoss

Reputation: 12273

The data structure to use depends on the purpose of your code... Lists usually do quite well, but if the graph is highly connected (most of the nodes are connected to most of the nodes), then a list is cumbersome, and a matrix of some kind is usually to be preferred.

For example, to use a matrix, keep a vector of nodes, then use a 2-dimensional vector of integers to reference the nodes.

Also, for making a lightweight class, you don't have to declare a class for nodes: you can provide functions for adding nodes and edges, and you can identify such elements with integers.

Having Node or Edge classes may be suitable if you plan to subclass them (for example, could be useful when doing a GUI which display a graph), but if you need the graph for some algorithms, identifying nodes/edges with integers is faster and simpler.

Upvotes: 0

Amit Portnoy
Amit Portnoy

Reputation: 6336

Here is a simple implementation (this should be good enough for many basic use cases):

public class Graph { 
  public List<Node> nodes = new ArrayList<Node>();
}                

public class Node{
  public List<Node> neighbors = new ArrayList<Node>();
 //here you can add stuff like "public boolean visited;", if your algorithm requires it
} 

(This is just an example - there are tons of ways to implement a graph structure).

Upvotes: 1

Related Questions