Skip to content

Instantly share code, notes, and snippets.

@prameshbajra
Created June 7, 2018 08:59
Show Gist options
  • Save prameshbajra/c77178a05a143199a8ea3b3690c10692 to your computer and use it in GitHub Desktop.
Save prameshbajra/c77178a05a143199a8ea3b3690c10692 to your computer and use it in GitHub Desktop.
Adjaceny Matric Implementation for Graph in JAVA.
package com.demo.advjava;
public class GraphImplementationAdjMat {
int[][] graph;
public GraphImplementationAdjMat(int vertices) {
graph = new int[vertices][vertices];
}
public void addEdge(int vertexOne, int vertexTwo) {
graph[vertexOne][vertexTwo] = 1;
graph[vertexTwo][vertexOne] = 1;
}
public void printGraph() {
int i, j;
for (i = 0; i < graph.length; i++) {
for (j = 0; j < graph.length; j++) {
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
GraphImplementationAdjMat gmat = new GraphImplementationAdjMat(Integer.parseInt(args[0]));
// Graph structure
// 0--1
// | /|
// |/ |
// 2--3--4
//
gmat.addEdge(0, 1);
gmat.addEdge(0, 2);
gmat.addEdge(2, 3);
gmat.addEdge(1, 3);
gmat.addEdge(3, 4);
gmat.printGraph();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment