Skip to main content

Designing graph in JAVA


How to design a Graph in JAVA:-

Vertex:-

package com.problems.graph;

public class Vertex{
  char label;
  boolean visited;
 
  public Vertex(char label){
   this.label=label;
   this.visited=false;
  }
}
Functions of Graphs
public class Graph {

 int maxsize=20;
 Vertex vertex[];
 int matrix[][];
 int vertexcount;
 Stack stackobj;

 public Graph()
 {
  vertex = new Vertex[maxsize];
  matrix=new int[maxsize][maxsize];
  vertexcount=0;
  for(int i=0;i<maxsize;i++)
  {
   for(int j=0;j<maxsize;j++)
   {
    matrix[i][j]=0;
   }
  }
  stackobj=new Stack();   
 }
 
 public void addVertex(char label)
 {
  vertex[vertexcount++]=new Vertex(label);
 }
 public void addEdge(int i,int j)
 {
  matrix[i][j]=1;
  matrix[j][i]=1;
 }
 
 public void displyVertex(int v)
 {
  System.out.println(vertex[v].label);
 }
 
 public int adjVertex(int v)
 {
  for(int i=0;i<maxsize;i++)
  {
   if(matrix[v][i]==1 && vertex[i].visited==false )
    return i;
  }
  return -1;
 }
}

Comments

.

Popular posts from this blog

Bubble Sort in JAVA

What is bubble sort?

It is a sorting technique that is based on the comparison.Here we compare adjacent element, if the first element is larger than the second we swap each other. We do the same procedure again and again until array do not sort completely.

Example:-
5 1 4 2 8



51428here pass is nothing but iterating the loops equal to number of elements in the array but if it already sorted before then we can break the loop anddo existPASS1 case0 1 //check 0 and first element15428 case1 2 //check 1 and 2 element14528 case2 314258 case3 414258 swap istruePASS2 //first pass completed now do second pass case0 114258 case1 212458 case2 312458 case3 412458 swap istrue PASS3 // third pass case0 112458 case1 212458 case2 312458 case3 412458 swap isfalse since swap is false we break from the loop and do not go for fourth and fifth pass
Program:-

package sorting;publicclassBubbleSort{//function to print arraypublicstaticvoidprint(int[] arr){for(int i=0;i<=arr.length-1;i++) Syst…