Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package graph;
- public class GraphRepresentationUsingAdjacencyMatrix {
- private int v;
- private int[][] adjacencyMatrix;
- GraphRepresentationUsingAdjacencyMatrix(int v){
- this.v = v;
- this.adjacencyMatrix = new int[v][v];
- }
- public void addEdge(int src, int dest) {
- //Considering Undirected Graph
- this.adjacencyMatrix[src][dest] = 1;
- //Remove this for directed graph
- this.adjacencyMatrix[dest][src] = 1;
- }
- public void printGraph() {
- for(int i = 0; i<this.v;i++) {
- for(int j = 0; j<this.v;j++) {
- if(this.adjacencyMatrix[i][j] == 1) {
- System.out.println("Path from "+i+" to "+j);
- }
- }
- }
- }
- public static void main(String[] args) {
- GraphRepresentationUsingAdjacencyMatrix g = new GraphRepresentationUsingAdjacencyMatrix(5);
- g.addEdge(0, 1);
- g.addEdge(0, 4);
- g.addEdge(1, 2);
- g.addEdge(1, 3);
- g.addEdge(1, 4);
- g.addEdge(2, 3);
- g.addEdge(3, 4);
- g.printGraph();
- }
- }
Add Comment
Please, Sign In to add comment