Click here to Skip to main content
15,936,014 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my complete code in java, i would like to apply Depth limited search on it. Can someone please help me?

output: S>A>B>C>D>G

Note: S(0) = Start, G(5) = Goal
The depth first search is applied using adj matrix.

Java
import java.util.Stack;
    
    
    public class DFS {

    Stack<Integer> st;
      int vFirst;

      int[][] adjMatrix;
      int[] isVisited = new int[6];

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[][] adjMatrix = {
               //S, A, B, C, D, G, 
                {0, 1, 0, 1, 0, 0},
                {1, 0, 1, 0, 1, 0},
                {0, 1, 0, 1, 0, 1},
                {1, 0, 1, 0, 1, 0},
                {0, 1, 0, 1, 0, 1},
                {0, 0, 1, 0, 1, 0},
                 };


      new DFS(adjMatrix);

    }

    public DFS(int[][] Matrix) {

         this.adjMatrix = Matrix;
         st = new Stack<Integer>();
         //int i;
         int[] node = {0, 1, 2, 3, 4, 5};
         int firstNode = node[0];
         depthFirst(firstNode, 6);



          }

          public void depthFirst(int vFirst,int n)
          {
          int v,i;
          char out=' ';

          st.push(vFirst);

          while(!st.isEmpty())
          {
              v = st.pop();
              if(v==0)out='S';
              else if(v==1)out='A';
              else if(v==2)out='B';
              else if(v==3)out='C';
              else if(v==4)out='D';
              else if(v==5)out='G';
              
              if(isVisited[v]==0)
              {
                  System.out.print("\n"+out);
                  isVisited[v]=1;
              }
              for ( i=0;i<n;i++)
              {
                  if((adjMatrix[v][i] == 1) && (isVisited[i] == 0))
                  {
                      st.push(v);
                      isVisited[i]=1;
                      if(i==0)out='S';
                      else if(i==1)out='A';
                      else if(i==2)out='B';
                      else if(i==3)out='C';
                      else if(i==4)out='D';
                      else if(i==5)out='G';
                      System.out.print("-> " + out);
                      v = i;
                  }
              }
              }
    }
    }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900