Skip to content

Instantly share code, notes, and snippets.

@theagoliveira
Created November 18, 2021 04:44
Show Gist options
  • Save theagoliveira/9273a3763aaa5d0a87f56d4f852bc310 to your computer and use it in GitHub Desktop.
Save theagoliveira/9273a3763aaa5d0a87f56d4f852bc310 to your computer and use it in GitHub Desktop.
A graph implementation in Java, based on The Algorithm Design Manual by Steven S. Skiena
package impl.graph;
class EdgeNode {
Integer y; /* adjacency info */
Integer weight; /* edge weight, if any */
EdgeNode next; /* next edge in list */
public EdgeNode(Integer y) {
this.y = y;
this.weight = null;
this.next = null;
}
public EdgeNode(Integer y, Integer weight) {
this.y = y;
this.weight = weight;
this.next = null;
}
public EdgeNode(Integer y, EdgeNode next) {
this.y = y;
this.weight = null;
this.next = next;
}
public EdgeNode(Integer y, Integer weight, EdgeNode next) {
this.y = y;
this.weight = weight;
this.next = next;
}
}
package impl.graph;
import java.util.Arrays;
public class Graph {
public static final Integer MAXV = 1000;
EdgeNode[] edges; /* adjcency info */
Integer[] degree; /* outdegree of each vertex */
Integer nvertices; /* number of vertices in graph */
Integer nedges; /* number of edges in graph */
boolean directed; /* is the graph directed? */
public Graph(Integer nvertices, boolean directed) {
this.edges = new EdgeNode[MAXV + 1];
this.degree = new Integer[MAXV + 1];
this.nvertices = nvertices;
this.nedges = 0;
this.directed = directed;
Arrays.fill(edges, null);
Arrays.fill(degree, 0);
}
public void insert(Integer x, Integer y, boolean directed) {
EdgeNode tempNode = new EdgeNode(y, null, edges[x]);
edges[x] = tempNode;
degree[x]++;
if (!directed) {
insert(y, x, !directed);
} else {
nedges++;
}
}
public void print() {
EdgeNode pointer;
System.out.println("No. of Vertices: " + nvertices);
System.out.println("No. of Edges: " + nedges);
System.out.println("Directed: " + directed);
System.out.println();
System.out.println("Edges:");
for (int i = 1; i <= nvertices; i++) {
System.out.print("[" + i + "]");
pointer = edges[i];
while (pointer != null) {
System.out.print(" -> " + pointer.y);
pointer = pointer.next;
}
System.out.print(" -> null");
System.out.println();
}
System.out.println();
System.out.println("Degrees:");
System.out.printf("V: ");
for (int i = 1; i <= nvertices; i++) {
System.out.printf("% 2d", i);
}
System.out.println();
System.out.printf("D: ");
for (int i = 1; i <= nvertices; i++) {
System.out.printf("% 2d", degree[i]);
}
System.out.println();
}
}
package impl.graph;
class GraphTest {
public static void main(String[] args) {
boolean directed = true;
var graph = new Graph(4, directed);
graph.insert(1, 2, directed);
graph.insert(2, 3, directed);
graph.insert(3, 4, directed);
graph.insert(4, 1, directed);
graph.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment