Depth first search tree

Hi,
I have stored some states in a vector (States are numbers). In my code i have printed out the parent nodes, the 2 elements after the parent nodes are there child.
The element placed at position 0 in the vector is the root. I do not know how to implement a depth first search tree to address unreachable node. In this case, parent node 5 is unreachable, from other nodes. But i do not know how to do this. I have spent ages reading tutorials/ book, but i cant seem to convert this knowledge into java. My code is very short and therefore easy to understand
import java.awt.*;
import java.util.*;
public class Vec{
public static void main(String argv[]){
    Vec v = new Vec();
    v.remove();
    }//End of main
public void remove(){
        Vector mv = new Vector();
        //Note how a vector can store objects
        //of different types
        mv.addElement(1);  // root and parent node of 2 elements below
        mv.addElement(2);  // child of above
        mv.addElement(1);  // child of above
        mv.addElement(2);  // parent of 2 elements below
        mv.addElement(4);
        mv.addElement(2);
        mv.addElement(3); // parent of 2 elements below
        mv.addElement(1);
        mv.addElement(3);
        mv.addElement(4); // parent of 2 elements below
        mv.addElement(3);
        mv.addElement(4);
        mv.addElement(5);  // parent of 2 elements below
        mv.addElement(2);
        mv.addElement(4);
// below identifys the parent nodes for you, but doesnt store them as parent nodes
                for(int i=0; i< mv.size(); i++){
        if (i % 3 == 0)
                  System.out.println(mv.elementAt(i));
   }//End of amethod
        

Ah ok, it's a graph and not a tree. In that case don't use the tree-code I posted, but model your graph as an adjacency matrix (AM) [1]. The AM for the graph you posted in reply #5 would look like this:
Node | 1  2  3  4  5
-----+--------------
   1 | 1  1  0  0  0
     |
   2 | 0  1  0  1  0
     |
   3 | 1  0  1  0  0
     |
   4 | 0  0  1  1  0
     |
   5 | 0  1  1  0  0You can implement this by using a simple 2D array of integers like this:class Graph {
    private int[][] adjacencyMatrix;
    public Graph(int numNodes) {
        adjacencyMatrix = new int[numNodes][numNodes];
    public void addEdge(int from, int to) {
        adjacencyMatrix[from-1][to-1] = 1;
    public boolean isReachable(Integer start, Integer goal) {
        // your algorithm here
        return false;
    public String toString() {
        StringBuilder strb = new StringBuilder();
        for(int i = 0; i < adjacencyMatrix.length; i++) {
            int[] row = adjacencyMatrix;
strb.append((i+1)+" | ");
for(int j = 0; j < row.length; j++) {
strb.append(adjacencyMatrix[i][j]+" ");
strb.append('\n');
return strb.toString();
public static void main(String[] args) {
Graph graph = new Graph(5);
graph.addEdge(1, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 2);
graph.addEdge(2, 4);
graph.addEdge(3, 1);
graph.addEdge(3, 3);
graph.addEdge(4, 3);
graph.addEdge(4, 4);
graph.addEdge(5, 2);
graph.addEdge(5, 3);
System.out.println("Adjacency Matrix:\n"+graph);
System.out.println("Is node 5 reachable from node 1? "+
graph.isReachable(new Integer(1), new Integer(5))); // should be false
System.out.println("Is node 1 reachable from node 5? "+
graph.isReachable(new Integer(5), new Integer(1))); // should be true: a path exists from 5 -> 3 -> 1 and 5 -> 2 -> 4 -> 3 -> 1
Good luck.
[1]
http://en.wikipedia.org/wiki/Adjacency_matrix
http://mathworld.wolfram.com/AdjacencyMatrix.html

Similar Messages

  • Depth First Search, Breadth First Search

    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Prod
    PL/SQL Release 10.2.0.5.0 - Production
    CORE     10.2.0.5.0     Production
    TNS for Linux: Version 10.2.0.5.0 - Production
    NLSRTL Version 10.2.0.5.0 - Production
    I
    have this table that form a tree where record with column value 'more_left' 0 is located more left than 1 (for example, record with id 2 has a parent id 1 and more left than record with id 7 that also has parent id 1):
    with t as(
      select 2 id,1 parent_id,0 most_left from dual
      union all
      select 7 id,1 parent_id,1 most_left from dual
      union all
      select 8 id,1 parent_id,2 most_left from dual
      union all
      select 3 id,2 parent_id,0 most_left from dual
      union all
      select 6 id,2 parent_id,1 most_left from dual
      union all
      select 9 id,8 parent_id,0 most_left from dual
      union all
      select 12 id,8 parent_id,1 most_left from dual
    union all
      select 4 id,3 parent_id,0 most_left from dual
      union all
      select 5 id,3 parent_id,1 most_left from dual
    union all
      select 10 id,9 parent_id,0  most_left from dual
      union all
      select 11 id,9 parent_id,1 most_left from dual
    select * from t;The problem is to show all the ids, using Breadth First Search and Depth First Search. Tx, in advance.
    Edited by: Red Penyon on Apr 12, 2012 3:39 AM

    Hi,
    I fail to understand how comes there is no row for ID=1 ?
    The topmost parent (the root) should be in the table also.
    For 11g, this would work (as long as the root is in the table) :Scott@my11g SQL>l
      1  WITH t AS
      2       (SELECT 1 ID, 0 parent_id, 0 most_left
      3          FROM DUAL
      4        UNION ALL
      5        SELECT 2 ID, 1 parent_id, 0 most_left
      6          FROM DUAL
      7        UNION ALL
      8        SELECT 7 ID, 1 parent_id, 1 most_left
      9          FROM DUAL
    10        UNION ALL
    11        SELECT 8 ID, 1 parent_id, 2 most_left
    12          FROM DUAL
    13        UNION ALL
    14        SELECT 3 ID, 2 parent_id, 0 most_left
    15          FROM DUAL
    16        UNION ALL
    17        SELECT 6 ID, 2 parent_id, 1 most_left
    18          FROM DUAL
    19        UNION ALL
    20        SELECT 9 ID, 8 parent_id, 0 most_left
    21          FROM DUAL
    22        UNION ALL
    23        SELECT 12 ID, 8 parent_id, 1 most_left
    24          FROM DUAL
    25        UNION ALL
    26        SELECT 4 ID, 3 parent_id, 0 most_left
    27          FROM DUAL
    28        UNION ALL
    29        SELECT 5 ID, 3 parent_id, 1 most_left
    30          FROM DUAL
    31        UNION ALL
    32        SELECT 10 ID, 9 parent_id, 0 most_left
    33          FROM DUAL
    34        UNION ALL
    35        SELECT 11 ID, 9 parent_id, 1 most_left
    36          FROM DUAL
    37  )
    38  select
    39  rt
    40  ,listagg(id,'-') within group (order by lvl,id) BFS
    41  ,listagg(id,'-') within group (order by pth,lvl) DFS
    42  from (
    43  SELECT id, connect_by_root(id) rt, sys_connect_by_path(most_left,'-') pth, level lvl, most_left
    44        FROM  t
    45  CONNECT by nocycle  prior ID = parent_id
    46  START WITH parent_id = 0
    47  )
    48* group by rt
    Scott@my11g SQL>/
            RT BFS                            DFS
             1 1-2-7-8-3-6-9-12-4-5-10-11     1-2-3-4-5-6-7-8-9-10-11-12But as long as you're 10g, that is no real help.
    I'll try to think of a way to get that with 10g.
    10g solution for DFS :Scott@my10g SQL>l
      1  WITH t AS
      2  (
      3       SELECT 1 ID, 0 parent_id, 0 most_left FROM DUAL UNION ALL
      4       SELECT 2 ID, 1 parent_id, 0 most_left FROM DUAL UNION ALL
      5       SELECT 7 ID, 1 parent_id, 1 most_left FROM DUAL UNION ALL
      6       SELECT 8 ID, 1 parent_id, 2 most_left FROM DUAL UNION ALL
      7       SELECT 3 ID, 2 parent_id, 0 most_left FROM DUAL UNION ALL
      8       SELECT 6 ID, 2 parent_id, 1 most_left FROM DUAL UNION ALL
      9       SELECT 9 ID, 8 parent_id, 0 most_left FROM DUAL UNION ALL
    10       SELECT 12 ID, 8 parent_id, 1 most_left FROM DUAL UNION ALL
    11       SELECT 4 ID, 3 parent_id, 0 most_left FROM DUAL UNION ALL
    12       SELECT 5 ID, 3 parent_id, 1 most_left FROM DUAL UNION ALL
    13       SELECT 10 ID, 9 parent_id, 0 most_left FROM DUAL UNION ALL
    14       SELECT 11 ID, 9 parent_id, 1 most_left FROM DUAL
    15  )
    16  select max(pth) DFS
    17  from (
    18  select sys_connect_by_path(id,'-') pth
    19  from (
    20  select id,pth,lvl,most_left, row_number() over (order by pth, lvl) rn
    21  from (
    22  select id, sys_connect_by_path(most_left,'-') pth, level lvl, most_left
    23  from t
    24  CONNECT by nocycle  prior ID = parent_id
    25  START WITH parent_id = 0
    26  )
    27  order by pth, lvl
    28  )
    29  connect by prior rn= rn-1
    30  start with rn=1
    31* )
    Scott@my10g SQL>/
    DFS
    -1-2-3-4-5-6-7-8-9-10-11-12------
    10g solution for BFS :Scott@my10g SQL>l
      1  WITH t AS
      2  (
      3       SELECT 1 ID, 0 parent_id, 0 most_left FROM DUAL UNION ALL
      4       SELECT 2 ID, 1 parent_id, 0 most_left FROM DUAL UNION ALL
      5       SELECT 7 ID, 1 parent_id, 1 most_left FROM DUAL UNION ALL
      6       SELECT 8 ID, 1 parent_id, 2 most_left FROM DUAL UNION ALL
      7       SELECT 3 ID, 2 parent_id, 0 most_left FROM DUAL UNION ALL
      8       SELECT 6 ID, 2 parent_id, 1 most_left FROM DUAL UNION ALL
      9       SELECT 9 ID, 8 parent_id, 0 most_left FROM DUAL UNION ALL
    10       SELECT 12 ID, 8 parent_id, 1 most_left FROM DUAL UNION ALL
    11       SELECT 4 ID, 3 parent_id, 0 most_left FROM DUAL UNION ALL
    12       SELECT 5 ID, 3 parent_id, 1 most_left FROM DUAL UNION ALL
    13       SELECT 10 ID, 9 parent_id, 0 most_left FROM DUAL UNION ALL
    14       SELECT 11 ID, 9 parent_id, 1 most_left FROM DUAL
    15  )
    16  select max(pth) BFS
    17  from (
    18  select sys_connect_by_path(id,'-') pth
    19  from (
    20  select id,pth,lvl,most_left, row_number() over (order by lvl, pth) rn
    21  from (
    22  select id, sys_connect_by_path(most_left,'-') pth, level lvl, most_left
    23  from t
    24  CONNECT by nocycle  prior ID = parent_id
    25  START WITH parent_id = 0
    26  )
    27  order by lvl, pth
    28  )
    29  connect by prior rn= rn-1
    30  start with rn=1
    31* )
    Scott@my10g SQL>/
    BFS
    -1-2-7-8-3-6-9-12-4-5-10-11There might certainly have better ways...

  • Depth First Search w/o Recursion

    I am trying to use Depth First Search for 2-D maze, and I was just wondering if there was a straight forward and easy way of doing DFS of a maze without using recursion. Or is recursion the really only way you do DFS without invoking a lot of messy variables to hold temporary information.

    itereation instead of recursion...can you be a little more discriptive.
    For recursion I can understand how it works because when you pop out of one recursive cycle you got to the next command. So basically
    move{
    if you can
    go left
    move()
    go right
    move()
    go up
    move()
    go down
    move()
    else
    pop out of recursion
    hopefully this pseudocode makes some sense. But absically lets say with my maze I go right 3 times then can't go right anymore...well when that happens it will try to go right, because after calling move() under "go left" the next step would just be to go left. But I don't see how this can be done iteratively. If somebody can explain it pseudocode that would be cool too.

  • When to go for Breadth first search over depth first search

    hi,
    under which scenarios breadth first search could be used and under which scenarios depth first search could be used?
    what is the difference between these two searches?
    Regards,
    Ajay.

    No real clear-cut rule for when to use one over the other. It depends on the nature of your search and where you would prefer to find results.
    The difference is that in breadth-first you first search all immidiate neighbours before searching their neighbours (sort of like preorder traversal). Whereas in depth-first you search some random (or otherwise selected) neighbour and then a neighbour of that node until you can't go deeper (i.e., you've searched a neighbour that has no other neighbours). This probably isn't a very clear explanation, perhaps you'll find this more helpful: http://www.ics.uci.edu/~eppstein/161/960215.html
    If you would prefer to find results closer to the origin node, breadth first would be better. If you would prefer to find results further away use depth first.

  • 8-Puzzle Depth First Search .. Need Help

    Hi, I have the following code for doing a depth first search on the 8-Puzzle problem
    The puzzle is stored as an object that contains an array such that the puzzle
    1--2--3
    4--5--6
    7--8--[] is stored as (1,2,3,4,5,6,7,8,0)
    The class for the puzzle is:
    class Puzzle implements {
         Puzzle parent;
         int[] pzle;
         int blank;
         Puzzle(int p1,int p2,int p3,int p4,int p5, int p6, int p7, int p8, int p9){
              pzle = new int[9];
              pzle[0] = p1; if(p1==0){ blank=0;}
              pzle[1] = p2; if(p2==0){ blank=1;}
              pzle[2] = p3; if(p3==0){ blank=2;}
              pzle[3] = p4; if(p4==0){ blank=3;}
              pzle[4] = p5; if(p5==0){ blank=4;}
              pzle[5] = p6; if(p6==0){ blank=5;}
              pzle[6] = p7; if(p7==0){ blank=6;}
              pzle[7] = p8; if(p8==0){ blank=7;}
              pzle[8] = p9; if(p9==0){ blank=8;}
         public Puzzle() {
         public boolean equals(Puzzle p){
              if(p == null) return false;
              for(int i =0;i<9;i++){
                   if(p.pzle!=pzle[i]){
                        return false;
              return true;
         public String toString(){
              return pzle[0] + "\t" + pzle[1] + "\t" + pzle [2] + "\n" +
                        pzle[3] + "\t" + pzle[4] + "\t" + pzle [5] + "\n" +
                        pzle[6] + "\t" + pzle[7] + "\t" + pzle [8] + "\n";
         public String printSolution(){
              String ret ="";
              Puzzle st = parent;
              while(st!=null){
                   ret = st + "\n=======================\n" + ret;
                   st = st.parent;
              ret=ret+this;
              return ret;
         public ArrayList<Puzzle> successors(){
              ArrayList<Puzzle> succ = new ArrayList<Puzzle>();
              int b = blank;
              if (((b-1) % 3) != 2 && b!=0) {
              Puzzle np1 = new Puzzle();
              np1.parent = this;
              np1.pzle = new int[9];
              for(int i =0;i<9;i++){
                   np1.pzle[i] = pzle[i];
              np1.pzle[b] = np1.pzle[b-1]; np1.pzle[b-1] = 0;
              np1.blank = b-1;
              if(!np1.equals(this.parent)){
              succ.add(np1);
              if (((b+1) % 3) != 0) {
              Puzzle np2 = new Puzzle();
              np2.parent = this;
              np2.pzle = new int[9];
              for(int i =0;i<9;i++){
                   np2.pzle[i] = pzle[i];
              np2.pzle[b] = np2.pzle[b+1]; np2.pzle[b+1] = 0;
              np2.blank = b+1;
              if(!np2.equals(this.parent)){
                   succ.add(np2);
              if (b-3 >= 0) {
              Puzzle np3 = new Puzzle();
              np3.parent = this;
              np3.pzle = new int[9];
              for(int i =0;i<9;i++){
                   np3.pzle[i] = pzle[i];
              np3.pzle[b] = np3.pzle[b-3]; np3.pzle[b-3] = 0;
              np3.blank = b-3;
              if(!np3.equals(this.parent)){
                   succ.add(np3);
              if (b+3 < 9) {
              Puzzle np4 = new Puzzle();
              np4.parent = this;
              np4.pzle = new int[9];
              for(int i =0;i<9;i++){
                   np4.pzle[i] = pzle[i];
              np4.pzle[b] = np4.pzle[b+3]; np4.pzle[b+3] = 0;
              np4.blank = b+3;
              if(!np4.equals(this.parent)){
                   succ.add(np4);
              return succ;
         The code for the DFS is      public static boolean DFS(Puzzle p, Puzzle goal, ArrayList<Puzzle> closed){
         if(p.equals(goal)){
              sol=p;
              return true;
         for(Puzzle pz : closed){
                   if(pz.equals(p)){
                        return false;
         closed.add(p);
                        //Generate all possible puzzles that can be attained
                        ArrayList<Puzzle> succ = p.successors();
                        for(Puzzle puz : succ){
                             if(DFS(puz,goal,closed)){ return true;}
              return false;
    }The problem is that when i run this on say the following start and goal:          Puzzle startP = new Puzzle(5,4,0,6,1,8,7,3,2);
              Puzzle goalP =new Puzzle(1,2,3,8,0,4,7,6,5);
              ArrayList<Puzzle> closed = new ArrayList<Puzzle>();
              startP.parent=null;
              boolean t = DFS(startP,goalP,closed);5-4-0
    6-1-8
    7-3-2 
    start and goal
    1-2-3
    8-0-4
    7-6-5
    it first takes foreever which is expected but it There should be 9! possible states correct? If I print out the size of the closed array (already seen states) it gets up to about 180000 and then returns with no solution found. But this is well under the 9! possible states...
    Its hard to know whats wrong and if it is even wrong.. but could someone please look at my code and see if something is off?
    I dont think the successor generator is wrong as I tested the blank in every space and it got the correct successors.
    Any ideas?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Puzzle(int p1,int p2,int p3,int p4,int p5, int p6, int p7, int p8, int p9){
              pzle = new int[9];
              pzle[0] = p1; if(p1==0){ blank=0;}
              pzle[1] = p2; if(p2==0){ blank=1;}
              pzle[2] = p3; if(p3==0){ blank=2;}
              pzle[3] = p4; if(p4==0){ blank=3;}
              pzle[4] = p5; if(p5==0){ blank=4;}
              pzle[5] = p6; if(p6==0){ blank=5;}
              pzle[6] = p7; if(p7==0){ blank=6;}
              pzle[7] = p8; if(p8==0){ blank=7;}
              pzle[8] = p9; if(p9==0){ blank=8;}
         }vs
    Puzzle(int...puzzle) {
      assert puzzle.length == 9;
      this.puzzle = Arrays.copyOf(puzzle, 9);
      for (int blank = 0; blank < 9; ++blank) if (puzzle[blank] == 0) break;
      // check values are 0...8
      Arrays.sort(puzzle); // sorts the original
      for (int i = 0; i < 9; ++i) assert puzzle[i] == i;
    Does anyone know if there are any simple applets or programs that do 8 Puzzle on any given start and finish state? Just to see the expected results.Not off hand, but you can always generate your starting state by moving backwards from the finish state.
    Also, I dont know..but are there some instances of an 8 Puzzle that cannot be solved at all?? IIRC, you can't transform 123 to 132 leaving the remainder unchanged, though I haven't checked.

  • Depth First Search help

    I have an assignment to do on a graph and have to apply depth first search so it ouputs the vertices in a order. I understand the algorithm and can do it on paper but i cannot do it in code so if anyone can help me on this. Here are the classes i am working with
    public class MatrixGraph extends AbstractGraph {
        private double[][] matrix;
        public MatrixGraph(int nV, boolean direct, boolean weight ){
            super(nV, direct, weight);
            matrix = new double[nV][nV];
            // if a weighted graph set all values to Double.POSITIVE_INFINITY 
            // otherwise set all values to 0
            //complete this code
        public boolean isEdge(int source, int dest) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void insert(Edge edge) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void remove(Edge edge) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void depthFirstTraversal(int start){
            //Output the vertices in depth first order
    public abstract class AbstractGraph implements Graph {
        private int numV;
        private boolean directed;
        private boolean weighted;
        public AbstractGraph(int nV, boolean direct, boolean weight){
            numV = nV;
            directed = direct;     
            weighted = weight;
        public int getNumV() {
            return numV;
        public boolean isDirected() {
            return directed;
        public boolean isWeighted() {
            return weighted;
    public interface Graph {
        //returns the number of vertices
        int getNumV();
        // determine if this is a directed graph
        boolean isDirected();
        // determine if this is a weighted graph
        boolean isWeighted();
        // determine if an edge exists between source and destination
        boolean isEdge(int source, int dest);
        void insert(Edge edge);
        void remove(Edge edge);
    }

    JavaLearner2009 wrote:
    public void depthFirstTraversal(int start){
    //Output the vertices in depth first order
    }I need help on this part i don't know how to write it.You mentioned you understand the algorithm and can do it on paper so what have you tried so far?
    If you are completely stuck on implementing the traversal in Java, provide pseudo code.
    Mel

  • Depth first search and breadth first search

    can anyone help for this program. can anyone give me a program for this without using an applet.
    thanks!!!

    can anyone help for this program. can anyone give me a
    program for this without using an applet.
    thanks!!!What are you talking about? What program? Depth-first means you recursively search from root to the first leaf, then go up one level, go down as far as you can, repeat. Breadth-first means you search every node on each level before going on to the next level.

  • Is SQR #include a depth first search or breadth first search alrgorithm

    Just wondering if SQR compiler is a dfs or bfs algorithm? I am guessing a dfs since includes can show up at the beginning or end of the sqr or sqc definition but position is relevant. So a few questions that branch off of that one.
    I have successfully included file filea.sqc and fileb.sqc in myfile.sqr, then included file subfile.sqc in both filea.sqc and fileb.sqc. There seemed to be no error message, so I am wondering how the file include works. I would think from a compiler point of view, if we included the same procedure or function twice, we should do one of three things - ignore the second instance (do nothing), override the first instance, or throw an error.
    So, anyone know how the compiler stack is built?

    The documentation doesn't help much, but if you want to prevent an include from being loaded more than once, you should be able to use a combination of compiler directives, i.e. #IFNDEF and #DEFINE.
    In your example, if you code subfile.sqc like
    #IFNDEF SUBFILE_INCLUDED
    #DEFINE SUBFILE_INCLUDED Y
    begin-procedure subfile_proc
    #ENDIFthen you should only get one copy of the code between the #IFNDEF-#ENDIF statements.
    You could probably use something similar to test how SQR handles multiple includes of the same file. Try something like
    #IFDEF SUBFILE_INCLUDED
    Display 'Subfile included twice'
    #ENDIF
    #IFNDEF SUBFILE_INCLUDED
    #DEFINE SUBFILE_INCLUDED Y
    #ENDIFand see if the message is displayed.
    Regards,
    Bob

  • DEPTH FIRST SEARCH

    hi,
    could u help me i want to read tree(node and edges betwwen node) i want to use DFS but it's unclear how to DFS to read data stored in file
    do I need to store tree information in file or create it in the same jave
    could u help me please

    Melanie_Green wrote:
    ali99099 wrote:
    hi,
    could u help me i want to read tree(node and edges betwwen node) i want to use DFS but it's unclear how to DFS to read data stored in file
    do I need to store tree information in file or create it in the same jave
    could u help me pleaseI don't think I can explain DFS better then the 1 quadrillion sites out there, however I could sum up the algorithm in less then a sentence. Left most child before Right child then Parent, rinse repeat.
    You also mention data is stored in a file, as we have NFC what type of data is stored in the file or how the data is stored I can not give you an answer.
    p.s. Sentences start with a capital letter.
    Melp.s. "then" is an adverb, you want the conjunction "than"

  • Depth First Search (LIFO) - stacked based

    Hi Everyone, 
    Herewith attached my workable Breadth fist search (FIFO) code - queue based. Now, I would like to change to LIFO - stacked based. 
    Anyone here can give some guideline on it?
    Many thanks.  
    Attachments:
    Version 1.zip ‏64 KB

    I've changed it to queue FIFO. but in the end, it won't show a complete path to reach the destination point. However, queue stack LIFO can show a complete path from starting point till the goal point.
    Does that means queue FIFO cannot be used in finding a complete path out? Is there any possible way for this method to find its way out? 
    Herewith attached queue FIFO. 
    Attachments:
    Queue FIFO.zip ‏64 KB

  • Using depth first traversal to add a new node to a tree with labels

    Hello,
    I'm currently trying to work my way through Java and need some advice on using and traversing trees. I've written a basic JTree program, which allows the user to add and delete nodes. Each new node is labelled in a sequential order and not dependent upon where they are added to the tree.
    Basically, what is the best way to add and delete these new nodes with labels that reflect their position in the tree in a depth-first traversal?
    ie: the new node's label will correctly reflect its position in the tree and the other labels will change to reflect this addition of a new node.
    I've searched Google and can't seem to find any appropriate examples for this case.
    My current code is as follows,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class BasicTreeAddDelete extends JFrame implements ActionListener
        private JTree tree;
        private DefaultTreeModel treeModel;
        private JButton addButton;
        private JButton deleteButton;
        private int newNodeSuffix = 1;
        public BasicTreeAddDelete() 
            setTitle("Basic Tree with Add and Delete Buttons");
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            JScrollPane scrollPane = new JScrollPane(tree);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            JPanel panel = new JPanel();
            addButton = new JButton("Add Node");
            addButton.addActionListener(this);
            panel.add(addButton);
            getContentPane().add(panel, BorderLayout.SOUTH);
            deleteButton = new JButton("Delete Node");
            deleteButton.addActionListener(this);
            panel.add(deleteButton);
            getContentPane().add(panel, BorderLayout.SOUTH);    
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(400, 300);
            setVisible(true);
        public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node" + newNodeSuffix++);
                      treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);               
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        public void removeSelectedNode()
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if (selectedNode != null)
                //get the parent of the selected node
                MutableTreeNode parent = (MutableTreeNode)(selectedNode.getParent());
                // if the parent is not null
                if (parent != null)
                    //remove the node from the parent
                    treeModel.removeNodeFromParent(selectedNode);
        public static void main(String[] arg) 
            BasicTreeAddDelete basicTree = new BasicTreeAddDelete();
    }      Thank you for any help.

    > Has anybody got any advice, help or know of any
    examples for this sort of problem.
    Thank you.
    Check this site: http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html

  • How to extend  breadth first Search for Binary Tree to any kind of Tree??

    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
    I have following code to successfully apply for breadth first Search in Binary Tree as follows,
    package a.border;
    import java.util.ArrayList;
    import java.util.LinkedList;
    public class Tree
        int root;
        Tree left;
        Tree right;
        static ArrayList<Integer> list = new ArrayList<Integer>();
        static ArrayList<Tree> treeList = new ArrayList<Tree>();
        private static LinkedList<Tree> queue = new LinkedList<Tree>();
         * @param root root value
         * @param left left node
         * @param right right node
        public Tree(int root, Tree left, Tree right)
            this.root = root;
            this.left = left;
            this.right = right;
        /** Creates a new instance of Tree
         * You really should know what this does...
         * @param root
        public Tree(int root)
            this.root = root;
            this.left = null;
            this.right = null;
         * Simply runs a basic left then right traversal.
        public void basicTraversal()
            //Check if we can go left
            if (left != null)
                left.basicTraversal();
            //Add the root
            list.add(root);
            //Check if we can go right
            if (right != null)
                right.basicTraversal();
        public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
            //Add the root to the arraylist, we know it is always the first entry.
            list.add(root);
            //Basically we add the first set of nodes into the queue for
            //traversing.
            //Query if left exists
            if (left != null)
                //Then add the node into the tree for traversing later
                queue.add(left);
            //Same for right
            if (right != null)
                queue.add(right);
            //Then we call the traverse method to do the rest of the work
            return traverse(list);
        private ArrayList<Integer> traverse(ArrayList<Integer> list)
            //Keep traversing until we run out of people
            while (!queue.isEmpty())
                Tree p = queue.remove();
                //Check if it has any subnodes
                if (p.left != null)
                    //Add the subnode to the back of the queue
                    queue.add(p.left);
                //Same for left
                if (p.right != null)
                    //Same here, no queue jumping!
                    queue.add(p.right);
                //Append to the ArrayList
                list.add(p.root);
            //And return
            return list;
         * Makes a tree and runs some operations
         * @param args
        public static void main(String[] args)
             *                             4
             *          t =           2       6
             *                      1   3    5   7
            Tree leaf6 = new Tree(1);
            Tree leaf7 = new Tree(3);
            Tree leaf8 = new Tree(5);
            Tree leaf9 = new Tree(7);
            Tree t4 = new Tree(2, leaf6, leaf7);
            Tree t5 = new Tree(6, leaf8, leaf9);
            Tree t = new Tree(4, t4, t5);
            t.basicTraversal();
            System.out.println("Here is basicTraversal ="+list.toString());
            list.clear();
            t.getBreadthTraversal(list);
            System.out.println("getBreadthTraversal= " +list.toString());
            list.clear();
        }Can Guru help how to update to any kind of tree??
    here this code is for the tree like:
             *                             4
             *          t =           2       6
             *                      1   3    5   7
             */But i hope the new code can handle tree like:
             *                             4
             *                           /   | \
             *                          /     |   \
             *          t =            2     8   6
             *                        / |  \    |    /| \
             *                      1 11  3 9   5 10  7
             */Thanks

    sunnymanman wrote:
    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
    What do all trees have in common? And what do all nodes in trees have in common?
    At least these things:
    interface Tree<T> {
        Node<T> getRoot();
    interface Node<T> {
        T getData();
        List<Node<T>> getChildren();
    }Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
    class BinaryTree<T extends Comparable<T>> implements Tree<T> {
        protected BTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class BTNode<T> implements Node<T> {
        private T data;
        private Node<T> left, right;
        public List<Node<T>> getChildren() {
            List<Node<T>> children = new ArrayList<Node<T>>();
            children.add(left);
            children.add(right);
            return children;
        public T getData() {
            return data;
    class NTree<T> implements Tree<T> {
        private NTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class NTNode<T> implements Node<T> {
        private T data;
        private List<Node<T>> children;
        public List<Node<T>> getChildren() {
            return children;
        public T getData() {
            return data;
    }Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
    interface Traverser<T> {
        List<Node<T>> traverse(T goal, Tree<T> tree);
    }And finally write an implementation for it:
    class BreathFirst<T> implements Traverser<T> {
        public List<Node<T>> traverse(T goal, Tree<T> tree) {
            Node<T> start = tree.getRoot();
            List<Node<T>> children = start.getChildren();
            // your algorithm here
            return null; // return your traversal
    }... which can be used to traverse any tree! Here's a small demo of how to use it:
    public class Test {
        public static void main(String[] args) {
            Tree<Integer> binTree = new BinaryTree<Integer>();
            // populate your binTree
            Tree<Integer> nTree = new NTree<Integer>();
            // populate your nTree
            Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
            // Look for integer 6 in binTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
            // Look for integer 6 in nTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
    }Good luck!

  • Depth/Breadth First Search

    Hello all,
    I am trying to figure out how to do a depth and breadth first search on a graph of Cities, as defined below. I think that I understand the searches, but I am having an extremely difficult time figuring out how to implement them.
    If anyone has any tips, suggestions, or hints (for some reason I think I'm probably just overlooking something simple), I would greatly appreciate them.
    Thanks for any help!
    * to represent an individual city
    public class City {
        String name;
        double latitude;
        double longitude;
        ArrayList<Edge> neighbors;
        //the constructor
        public City(String name, double latitude, double longitude){
            this.name = name;
            this.latitude = latitude;
            this.longitude = longitude;
            this.neighbors = new ArrayList<Edge>();
        //to check if this city is equal to that given city
        public boolean same(City c){
            return this.name.equals(c.name) && this.latitude == c.latitude &&
                this.longitude == c.longitude;
    * to represent an edge between two cities
    public class Edge {
        City city1;
        City city2;
        double dist;
        boolean visited;
        public Edge(City city1, City city2){
            this.city1 = city1;
            this.city2 = city2;
            this.dist = this.distTo();
            this.visited = false;
         * to find the distance between the two cities in an edge
        public double distTo(){
            return Math.sqrt(((this.city1.latitude - this.city2.latitude) *
                    (this.city1.latitude - this.city2.latitude)) +
                    ((this.city1.longitude - this.city2.longitude) *
                    (this.city1.longitude - this.city2.longitude)));
    * to represent a path between two cities as a list
    * of edges
    public class Graph {
        ArrayList<Edge> alist;
        public Graph(ArrayList<Edge> alist){
            this.alist = alist;
    }

    http://en.wikipedia.org/wiki/Breadth-first_search (includes algorithm)

  • Searching a binary search tree  written to a file

    hello
    I have a binary search tree which has 10 levels. Now I want to search a node
    after writing all the nodes to a file.
    Can anyone help me in doing this. A sample code would be great ...
    Thanks
    K

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

  • Binary search tree - writing to a file in alphabetic order words from tree

    Hi
    I have written a program that will read a list of words from a file, insert these into a binary search tree, write words from the tree to another file, so that the resulting list contains words in ascending order. My input file Alpha1.txt contains the following contents in the order and format given (one word per line):
    Dawn
    Dave
    Mike
    Beth     
    David
    Gina
    Pat
    Cindy
    Sue
    My program is supposed to be producing an alphabetical list of these words in another file "final.txt".
    Instead it gives me the following list:
    Dave Beth David Gina Cindy Sue Pat Mike Dawn
    This is obviously wrong, right? My correct list in "final.txt" should be
    Beth Cindy Dave David Dawn Gina Mike Pat Sue
    I am not sure what is wrong with my code which I reproduce below:
    import java.io.*;
    import java.util.*;
    //read Java Developer's Almanac from exampledepot.com
    //Read this: http://en.wikipedia.org/wiki/Tree_traversal
    /**preorder(node)
      print node.value
      if node.left  ? null then preorder(node.left)
      if node.right ? null then preorder(node.right)
    public class AlphabeticBinarySortTree
         private static TreeNode root;
         private static TreeNode runner;
         static String[] alphaArray;
         static int alphaCounter;
         private static TreeNode alphaRunner;
         //Inner class
              private static class TreeNode
                   String word;
                   TreeNode left;
                   TreeNode right;
                   int count;
                   public TreeNode(String word)
                        this.word = word;
                        left = null;
                        right = null;
                   public void insertAll(TreeNode newNode)
                        if(newNode.word.compareTo(runner.word) < 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.left == null)
                                  runner.left = newNode;
                                  runner = runner.left;
                             else
                                  insertAll(newNode);
                        else if(newNode.word.compareTo(runner.word) > 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.right == null)
                                  runner.right = newNode;
                                  runner = runner.right;
                             else
                                  insertAll(newNode);
                        else
                             count++;
                   }// end method insertAll
                   // Recursively print words (with counts) in sorted order
                     public static void printInPreOrder(TreeNode root)
                             System.out.println(root.word + " ");
                             if(root.left != null)
                                   printInPreOrder(root.left);
                              if(root.right != null)
                                   printInPreOrder(root.right);
                       } //end method printInPreOrder()
                     //called from inside main
                    public static void arrangeInAscendingOrder(TreeNode root, PrintWriter pWriter)
                             if(root.left != null)
                                   arrangeInAscendingOrder(root.left, pWriter);
                             System.out.println();
                             System.out.println();
                             System.out.println(root.word + " ");
                             pWriter.write(root.word + " ");
                             if(root.right != null)
                                  arrangeInAscendingOrder(root.right, pWriter);
              }//end inner class TreeNode
         public AlphabeticBinarySortTree()
              root = null;
         //belong to the outer class
         public static void main(String[] args)
              System.out.println("This program reads text from a file that it will parse. ");
              System.out.println("In doing so, it will eliminate duplicate strings and ");
              System.out.println("pick up only unique strings.These strings will be in a ");
              System.out.println("stored in alphabetical order in a binary Search tree before they are ");
              System.out.println("written out to another text file in alphabetic order");
              //open the file for reading
              try
                   BufferedReader bReader = new BufferedReader(new FileReader("Alpha1.txt"));
                   String words;
                   int count;
                   //System.out.println("A test to inspect the contents of words: " + words);
                   //System.out.println("Words =" + words);
                   count = 0;
                   //why is there an endless loop when
                   //I use "while(str != null)
                   StringTokenizer st;
                   st = null;
                   //based on http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
                   while ((words = bReader.readLine()) != null)
                        st = new StringTokenizer(words);
                       while(st.hasMoreTokens())
                            //shiffman.net/teaching/a2z/concordance
                            String token = st.nextToken();
                            System.out.println("Token = " +token);
                            AlphabeticBinarySortTree.initiateInsert(token);
                            //count the number of tokens in the string
                            count++;
                        }//end inner while
                   }//end outer while
                   System.out.println("Here are the contents of your tree:");
                   //System.out.println("before the call to print()");
                   print();
                   System.out.println("the no of words in the file is: " + count);
                   bReader.close();
              }//end of try
              catch(IOException exception)
                   exception.printStackTrace();
                   /**try
                             FileWriter fWriter = new FileWriter("final.txt");
                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                             PrintWriter pWriter = new PrintWriter(bWriter);
                   catch(IOExcepion exception)
                        exception.printStackTrace();
         } // end main here
         //this method belongs to the outer class
         static void initiateInsert(String word)
              //TreeNode is also static by the way
              TreeNode newNode = new TreeNode(word);
              if(root == null)
                   root = newNode;
                   System.out.println("root.word = " + root.word);
                   runner = root;
              else
                   runner.insertAll(newNode);
         // Start the recursive traversing of the tree
            //without the access specifier 'static'
            //I would get the following error message
            //AlphabeticBinarySortTree.java:119: non-static method print() cannot be referenced from a static context
            public static void print()
                //System.out.println("**********AM I INSIDE THE PRINT() METHOD? ********");
               if (root != null)
                    //System.out.println("++++++++ AM I INSIDE THE IF BLOCK OF THE PRINT() METHOD? +++++++");
                    //System.out.println("Inside THE IF BLOCK OF print() BUT BEFORE THE CALL TO printInPreOrder(),root.word = " + root.word);
                  AlphabeticBinarySortTree.TreeNode.printInPreOrder(root);
                  //open the file for writing
                              try
                                             FileWriter fWriter = new FileWriter("final.txt");
                                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                                             PrintWriter pWriter = new PrintWriter(bWriter);
                                             AlphabeticBinarySortTree.TreeNode.arrangeInAscendingOrder(root, pWriter);
                                          pWriter.close();
                              catch(IOException eException)
                                   eException.printStackTrace();
               }//end of if block
            } // end of method print
    }//end outer enclosing class here--------
    All help is highly appreciated. Thanks for your time and consideration.

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

Maybe you are looking for

  • Server loses internet connection after creating virtual switch in hyper-v

    On a fresh Server 2012R2 Essentials install, I set up Hyper-v and created an external virtual switch. Connection to the vm is good but Health Report no shows loss of internet connectivity and that the router is incorrectly setup.  However, I still ha

  • I converted a trial of Acrobat XI Pro to a purchase, monthly subscription.

    I trialed Adobe Acobat XI Pro.  Really liked it.  Now I can't open any PDF's without the trial expiry notification coming on.  I get asked if I want to continue or not.  When I say no, it just quits and the doc doesn't open.  When I click through yes

  • Keeping library problem?

    I have a problem with windows xp and to fix it I have to reset it to factory defaults. I have a external hard drive to save my music while I clean my hard drive. Does anyone know how to keep not only the playlists but also other data such as the play

  • Cannot create OD master in ML server

    Hi, I have 2 servers configured on 10.8.2 and they won't create a OD master. DNS checks out fine (sudo changeip -checkhostname) I removed all the certificates. I even removed the folder "certificates" in /private/etc/ but no luck. Here is the output

  • How can I be sure that changing from ADSL to Infin...

    Hi, I would like to upgrade from ADSL to Infinity, but I am not convinced there will be any real benefit to me and BT are not being helpful. I am currently with Talk Talk and consistently get between 19.5 and 20 meg sync speeds. I don't know where my