1

As the title says.. What is the most efficient way to store a connected graph in java?

For example lets say I have multiple locations connecting to each other in various ways and I have to traverse through the graph to see if it's connected.. any help/comment would be helpful thanks!

xiao
  • 1,718
  • 4
  • 23
  • 31

5 Answers5

5

One often used representation is a matrix (two dimensional array) indexed by all the nodes in the graph, where M[i,j] == true if there is a directed edge from node i to j. A variation on the theme is to store the length / weight of the edge between the two nodes (where a missing edge may be represented by the value -1).

Péter Török
  • 114,404
  • 31
  • 268
  • 329
1

use an adjacency matrix without the symmetry, thereby representing direction instead of simple adjacency.

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
1

Using an incidence or adjacency matrix will do the trick.

If you use an adjacency matrix, a sparse matrix might be efficient to use, if you have a lot of nodes. Colt provides a sparse matrix implementation. Info taken from this SO post.

Also, I've used JUNG sucessfully before, so you might want to take a peek under the hood to see how they've implemented directed graphs.

Community
  • 1
  • 1
darioo
  • 46,442
  • 10
  • 75
  • 103
0

For lookup efficiency - use a boolean matrix (true if there is an arc connecting the nodes, false if there isn't). For memory efficiency define one of your object properties as a (dynamic) list of objects its pointing to. Note the latter will only help if you have a LOT of nodes in your graph.

Assaf
  • 1,336
  • 1
  • 10
  • 17
0

Am I missing something? The data is already a graph, just serialize it.For the question as written talk of matrices is completely premature.

CurtainDog
  • 3,175
  • 21
  • 17