Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active April 1, 2022 16:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/1371de0b6b68a4e5b8bf48c7c7a5be4d to your computer and use it in GitHub Desktop.
Save thmain/1371de0b6b68a4e5b8bf48c7c7a5be4d to your computer and use it in GitHub Desktop.
public class GraphAjdacencyMatrix {
int vertex;
int matrix[][];
public GraphAjdacencyMatrix(int vertex) {
this.vertex = vertex;
matrix = new int[vertex][vertex];
}
public void addEdge(int source, int destination) {
//add edge
matrix[source][destination]=1;
//add bak edge for undirected graph
matrix[destination][source] = 1;
}
public void printGraph() {
System.out.println("Graph: (Adjacency Matrix)");
for (int i = 0; i < vertex; i++) {
for (int j = 0; j <vertex ; j++) {
System.out.print(matrix[i][j]+ " ");
}
System.out.println();
}
for (int i = 0; i < vertex; i++) {
System.out.print("Vertex " + i + " is connected to:");
for (int j = 0; j <vertex ; j++) {
if(matrix[i][j]==1){
System.out.print(j + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
GraphAjdacencyMatrix graph = new GraphAjdacencyMatrix(5);
graph.addEdge(0, 1);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.printGraph();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment