Guest User

Untitled

a guest
Jun 18th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. package graph;
  2.  
  3. public class GraphRepresentationUsingAdjacencyMatrix {
  4.  
  5. private int v;
  6.  
  7. private int[][] adjacencyMatrix;
  8.  
  9. GraphRepresentationUsingAdjacencyMatrix(int v){
  10. this.v = v;
  11. this.adjacencyMatrix = new int[v][v];
  12. }
  13.  
  14. public void addEdge(int src, int dest) {
  15. //Considering Undirected Graph
  16. this.adjacencyMatrix[src][dest] = 1;
  17. //Remove this for directed graph
  18. this.adjacencyMatrix[dest][src] = 1;
  19. }
  20.  
  21. public void printGraph() {
  22. for(int i = 0; i<this.v;i++) {
  23. for(int j = 0; j<this.v;j++) {
  24. if(this.adjacencyMatrix[i][j] == 1) {
  25. System.out.println("Path from "+i+" to "+j);
  26. }
  27. }
  28. }
  29. }
  30.  
  31. public static void main(String[] args) {
  32. GraphRepresentationUsingAdjacencyMatrix g = new GraphRepresentationUsingAdjacencyMatrix(5);
  33. g.addEdge(0, 1);
  34. g.addEdge(0, 4);
  35. g.addEdge(1, 2);
  36. g.addEdge(1, 3);
  37. g.addEdge(1, 4);
  38. g.addEdge(2, 3);
  39. g.addEdge(3, 4);
  40. g.printGraph();
  41. }
  42.  
  43.  
  44.  
  45. }
Add Comment
Please, Sign In to add comment