Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some ways I can represent a weighted, directed graph in Java?

Tags:

java

graph

I can't use any external libraries, so I'm trying to think of some ways to build the data structure myself. I was thinking maybe something like this:

public class Node{
    Set<Edge> adjacent;
    int value;
}

public class Edge{
    Node target;
    int weight;
}

But I'm guessing there's probably a better way to do it.

My eventual use for this graph is to run the Bellman Ford algorithm on it, but I obviously need a functioning graph first!

like image 275
Hoser Avatar asked Nov 19 '12 03:11

Hoser


People also ask

How do you represent a directed weighted graph?

A weighted graph refers to one where weights are assigned to each edge. Weighted graphs can be represented in two ways: Directed graphs where the edges have arrows that show path direction. Undirected graphs where edges are bi-directional and have no arrows.

What are the different ways to represent the graph in memory?

There are three ways to store a graph in memory: Nodes as objects and edges as pointers. A matrix containing all edge weights between numbered node x and node y. A list of edges between numbered nodes.


Video Answer


3 Answers

The answer depends a lot on the algorithms that you are planning to apply to your graphs.

There are two common ways to represent a graph - an adjacency list and an adjacency matrix. In your case, and adjacency matrix is a square array of integers representing weights. Your representation uses an adjacency list.

There are algorithms that work better on adjacency matrixes (e.g. Floyd-Warshall algorithm). Other algorithms work better on adjacency lists (e.g. Dijkstra's algorithm). If your graph is sparse, using adjacency matrix may be prohibitive.

like image 105
Sergey Kalinichenko Avatar answered Dec 01 '22 01:12

Sergey Kalinichenko


As usual, you can represent graphs as Adjacency Lists or Adjacency Matrices. The choice really depends on the details of your problem.

Using an Adjacency Matrix, you could simply have a matrix of integers, representing the weight.

If you decide to have an Adjacency List, you could simply store a list of list of integers (assuming the nodes of your graph are identified by an integer value), similar to what you've done.

like image 33
leo Avatar answered Nov 30 '22 23:11

leo


You can use a node as in an unweighted graph, holding a list of nodes to which it is connected,and additionally add the weights associated with the connections as:

public class Node{
    int value;
    HashMap<Node,Integer> adjacency;
}
like image 40
Sumit Avatar answered Dec 01 '22 01:12

Sumit