mdmamunkhan

DFS_print parent of each node_sir

Feb 15th, 2019
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. package dfs;
  2. /*
  3.  * @author mamun
  4.  */
  5. public class DFS {
  6.  
  7.     public static void main(String[] args) {
  8.        
  9.         dfs obj = new dfs();
  10.         obj.print();
  11.  
  12.     }    
  13. }
  14.  
  15. //Call another java class
  16. package dfs;
  17. /*
  18.  * @author mamun
  19.  */
  20. public class dfs {    
  21.     int g[][] = {   {0,1,0,0,1,1},  //0
  22.                     {1,0,1,0,0,0},  //1
  23.                     {0,1,0,1,0,0},  //2
  24.                     {0,0,1,0,0,0},  //3
  25.                     {1,0,0,0,0,0},  //4
  26.                     {1,0,0,0,0,0}   //5      
  27.                 };
  28.     int visited[] ={0,0,0,0,0,0};
  29.     int parent [];
  30.     int N;
  31.    
  32.     dfs(){
  33.         N=6;
  34.         parent = new int [N]; // parent will an one dimensional array
  35.        
  36.         mydfs(0); //call dfs by first node 0
  37.        
  38.     }
  39.    
  40.     void mydfs(int s)
  41.     {
  42.        visited[s] =1;
  43.        for (int v=0; v<N;v++)   // N is node number
  44.        {
  45.            if (g[s][v] ==1 && visited[v]==0)
  46.            {
  47.                parent[v]=s;
  48.                mydfs(v); // call dfs again by current node
  49.            }
  50.        }
  51.     }
  52.     void print()
  53.     {
  54.         System.out.println("Node\tParent");
  55.         for (int i=0;i<N;i++)
  56.         {
  57.             System.out.println(""+i+"\t"+parent[i]);
  58.         }
  59.     }
  60.    
  61. }
Add Comment
Please, Sign In to add comment