DEV Community

Janardhan Pulivarthi
Janardhan Pulivarthi

Posted on • Edited on

Day 15 of 100 - Java: Graph data structure

Graph data structure with Java


class Graph {

  class Edge {
    int src, dest;
  }

  // Number of vertices and edges
  int vertices, edges;

  Edge[] edge;

  Graph(int vertices, int edges) {
    this.vertices = vertices;
    this.edges = edges;

    edge = new Edge[edges];
    for (int i = 0; i < edges; i++) {
      edge[i] = new Edge();
    }
  }

  public static void main(String[] args) {
    int numVertices = 5;
    int numEdges = 7;
    Graph g = new Graph(numVertices, numEdges);

    g.edge[0].src = 1;
    g.edge[0].dest = 2;

    g.edge[1].src = 1;
    g.edge[1].dest = 3;

    g.edge[2].src = 1;
    g.edge[2].dest = 4;

    g.edge[3].src = 2;
    g.edge[3].dest = 3;

    g.edge[4].src = 2;
    g.edge[4].dest = 4;

    g.edge[5].src = 3;
    g.edge[5].dest = 5;

    g.edge[6].src = 4;
    g.edge[6].dest = 5;

    for (int i = 0; i < numEdges; i++) {
      System.out.println(g.edge[i].src + " - " + g.edge[i].dest);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

https://github.com/j143/java-graph-datastructure-example

Java Collections conversions

Java List or ArrayList to Array

ArrayList homekeys = new ArrayList<> ();

homekeys.add("A");
homekeys.add("S");
homekeys.add("D");
homekeys.add("F");

// Create new Array

String[] homekeysArray = new String[homekeys.size()];

homekeys.toArray(homekeysArray);

Enter fullscreen mode Exit fullscreen mode

But, the other way around is simple

// import java.util.Arrays;

String[] array = {"A", "S", "D", "F"};

List languages = new ArrayList<> (Arrays.asList(array))
Enter fullscreen mode Exit fullscreen mode

Based on the above learning I have solved https://leetcode.com/problems/rearrange-array-elements-by-sign/ but got Time Limit Exceeded.

Top comments (0)