Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package bfsdfs;
- import java.util.Scanner;
- public class Main
- {
- static int top=-1,front=-1,rear=-1;
- static int[][] a=new int[20][20];
- static int[] q=new int[20];
- static int[] stack=new int[20];
- static int[] vis = new int[20];
- static void bfs(int s,int n)
- {
- int p,i;
- add(s);
- vis[s]=1;
- p=delete();
- if(p!=0)
- System.out.format(" %d",p);
- while(p!=0)
- {
- for(i=1; i<=n; i++)
- if((a[p][i]!=0)&&(vis[i]==0))
- {
- add(i);
- vis[i]=1;
- }
- p=delete();
- if(p!=0)
- System.out.format(" %d ",p);
- }
- for(i=1; i<=n; i++)
- if(vis[i]==0)
- bfs(i,n);
- }
- static void add(int item)
- {
- if(rear==19)
- System.out.format("QUEUE FULL");
- else
- {
- if(rear==-1)
- {
- q[++rear]=item;
- front++;
- }
- else
- q[++rear]=item;
- }
- }
- static int delete()
- {
- int k;
- if((front>rear)||(front==-1))
- return(0);
- else
- {
- k=q[front++];
- return(k);
- }
- }
- //***************DFS(depth-first search) code******************//
- static void dfs(int s,int n)
- {
- int i,k;
- push(s);
- vis[s]=1;
- k=pop();
- if(k!=0)
- System.out.format(" %d ",k);
- while(k!=0)
- {
- for(i=1; i<=n; i++)
- if((a[k][i]!=0)&&(vis[i]==0))
- {
- push(i);
- vis[i]=1;
- }
- k=pop();
- if(k!=0)
- System.out.format(" %d ",k);
- }
- for(i=1; i<=n; i++)
- if(vis[i]==0)
- dfs(i,n);
- }
- static void push(int item)
- {
- if(top==19)
- System.out.format("Stack overflow ");
- else
- stack[++top]=item;
- }
- static int pop()
- {
- int k;
- if(top==-1)
- return(0);
- else
- {
- k=stack[top--];
- return(k);
- }
- }
- public static void main(String[] args)
- {
- Scanner scanner = new Scanner(System.in);
- int n,i,s,ch,j;
- char c,dummy;
- System.out.format("\nENTER THE NUMBER VERTICES : ");
- n = scanner.nextInt();
- for(i=1; i<=n; i++)
- {
- for(j=1; j<=n; j++)
- {
- System.out.format("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 : ",i,j);
- a[i][j] = scanner.nextInt();
- }
- }
- System.out.format("THE ADJACENCY MATRIX IS\n");
- for(i=1; i<=n; i++)
- {
- for(j=1; j<=n; j++)
- {
- System.out.format(" %d",a[i][j]);
- }
- System.out.format("\n");
- }
- do
- {
- for(i=1; i<=n; i++)
- vis[i]=0;
- System.out.format("\nMENU");
- System.out.format("\n1.B.F.S");
- System.out.format("\n2.D.F.S");
- System.out.format("\nENTER YOUR CHOICE : ");
- ch = scanner.nextInt();
- System.out.format("ENTER THE SOURCE VERTEX : ");
- s = scanner.nextInt();
- switch(ch)
- {
- case 1:
- bfs(s,n);
- break;
- case 2:
- dfs(s,n);
- break;
- }
- System.out.format("\nDO U WANT TO CONTINUE(Y/N) ? ");
- c = scanner.next().charAt(0);
- }
- while((c=='y')||(c=='Y'));
- }
- }
Add Comment
Please, Sign In to add comment