javavertexjgraphtlabelinggraph-coloring

How to label or color a vertex using jgrapht libraries?


I am interested in writing a graph coloring algorithm using various types of directed and undirected graph classes provided by jgrapht. None of them seem to have an easy ability to do this within the graph class itself (e.g. DirectedSimpleGraph).

My goal is to be able to traverse the graph object, and add/change various labels or colors to the vertices, without the need to store the vertex information outside the object itself - i.e. I would like to use or create methods such as "DirectedSimpleGraph.setColorToVertex(v, c), where v is a vertex. and c is the color which perhaps would be defined as an integer. Any leads or best practices advice would be greatly appreciated.


Solution

  • The typical way to be able to colour or label a vertex is to supply your own Vertex class to jgrapht that stores whatever you need. For example,

    public class MyVertex {
      public String colour;
    }
    
    SimpleGraph<MyVertex, DefaultEdge> g = 
        new SimpleGraph<MyVertex,DefaultEdge>(DefaultEdge.class);
    MyVertex v1 = new MyVertex();
    MyVertex v2 = new MyVertex();
    
    g.addVertex(v1);
    g.addVertex(v2);
    
    DefaultEdge edge = g.addEdge(v1, v2);
    
    //traverse graph
    Graphs.getOppositeVertex(g, edge, v1).colour = "red";
    

    This way, you don't need to use an external mechanism (e.g. hash map) to keep track of vertex colours / labels.