Example: Implement Graph Data Structure
class Graph {
// inner class
// to keep track of edges
class Edge {
int src, dest;
}
// number of vertices and edges
int vertices, edges;
// array to store all edges
Edge[] edge;
Graph(int vertices, int edges) {
this.vertices = vertices;
this.edges = edges;
// initialize the edge array
edge = new Edge[edges];
for(int i = 0; i < edges; i++) {
// each element of the edge array
// is an object of Edge type
edge[i] = new Edge();
}
}
public static void main(String[] args) {
// create an object of Graph class
int noVertices = 5;
int noEdges = 8;
Graph g = new Graph(noVertices, noEdges);
// create graph
g.edge[0].src="/?originalUrl=https%3A%2F%2Fwww.programiz.com%2F1%3B%2520%2520%2520%2F%2F%2520edge%25201---2%2520%2520%2520%2520g.edge%5B0%5D.dest%2520%3D%25202%3B%2520%2520%2520%2520g.edge%5B1%5D.src%2520%3D%25201%3B%2520%2520%2520%2F%2F%2520edge%25201---3%2520%2520%2520%2520g.edge%5B1%5D.dest%2520%3D%25203%3B%2520%2520%2520%2520g.edge%5B2%5D.src%2520%3D%25201%3B%2520%2520%2520%2F%2F%2520edge%25201---4%2520%2520%2520%2520g.edge%5B2%5D.dest%2520%3D%25204%3B%2520%2520%2520%2520g.edge%5B3%5D.src%2520%3D%25202%3B%2520%2520%2520%2F%2F%2520edge%25202---4%2520%2520%2520%2520g.edge%5B3%5D.dest%2520%3D%25204%3B%2520%2520%2520%2520g.edge%5B4%5D.src%2520%3D%25202%3B%2520%2520%2520%2F%2F%2520edge%25202---5%2520%2520%2520%2520g.edge%5B4%5D.dest%2520%3D%25205%3B%2520%2520%2520%2520g.edge%5B5%5D.src%2520%3D%25203%3B%2520%2520%2520%2F%2F%2520edge%25203---4%2520%2520%2520%2520g.edge%5B5%5D.dest%2520%3D%25204%3B%2520%2520%2520%2520g.edge%5B6%5D.src%2520%3D%25203%3B%2520%2520%2520%2F%2F%2520edge%25203---5%2520%2520%2520%2520g.edge%5B6%5D.dest%2520%3D%25205%3B%2520%2520%2520%2520g.edge%5B7%5D.src%2520%3D%25204%3B%2520%2520%2520%2F%2F%2520edge%25204---5%2520%2520%2520%2520g.edge%5B7%5D.dest%2520%3D%25205%3B%2520%2520%2520%2520%2F%2F%2520print%2520graph%2520%2520%2520%2520for(int%2520i%2520%3D%25200%3B%2520i%2520%26lt%3B%2520noEdges%3B%2520i%2B%2B)%2520%257B%2520%2520%2520%2520%2520%2520System.out.println(g.edge%5Bi%5D.src%2520%2B" - " + g.edge[i].dest);
}
}
}
Output
1 - 2 1 - 3 1 - 4 2 - 4 2 - 5 3 - 4 3 - 5 4 - 5
In the above example, we have implemented the graph data structure in Java. To learn more about graphs, visit Graph Data Structure.