2015-05-11 2 views
3

Мой основной код .java нижекод не обходе корректно при использовании BFS

package phase4and5; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.LinkedList; 
import java.util.Queue; 

public class phase4and5 { 

    public static void CreateGraph(File a, graph g) throws IOException { 

     //ArrayList<node> NodeOfGraph = new ArrayList<node>(); 
     String st1 , st2 , line; 
     Integer vs , es; 
     try { 
      BufferedReader br = new BufferedReader(new FileReader(a)); 
      st1 = br.readLine(); 
      st2 = br.readLine(); 
      vs = Integer.parseInt(st1); 
      es = Integer.parseInt(st2); 
      while ((line = br.readLine()) != null) { 
       String[] splited = line.split("\\s+"); 
       Integer NameV = Integer.valueOf(splited[0]); 
       node vTemp = new node(NameV); 
       Integer AdjV = Integer.valueOf(splited[1]); 
       node AdjTemp = new node(AdjV); 
       if(g.InGraph(NameV) == false) { 
        vTemp.addChildnode(AdjTemp); 
        g.addnode(vTemp); 
        // NodeOfGraph.add(vTemp); 
       } else { 
        g.FindNode(NameV).addChildnode(AdjTemp); 
       } 
      }  
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public static void bfs(node root) { 
     //Since queue is a interface 
     Queue<node> queue = new LinkedList<node>(); 

     if(root == null) return; 

     root.State = state.Visited; 
     //Adds to end of queue 
     queue.add(root); 
     Integer count = 0; 
     while(!queue.isEmpty()) { 
      count++; 
      System.out.println("count : " + count); 
      //removes from front of queue 
      node r = queue.remove(); 
      System.out.println(r.getVertex() + "\t"); 
      // System.out.println(r.getChild().get(0).getVertex() + "\t"); 
      // Visit child first before grandchild 
      for(node n: r.getChild()) { 
       System.out.println("n "+n.getVertex()); 
       if(n.State == state.Unvisited) { 
        queue.add(n); 
        n.State = state.Visited; 
       } 
      } 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     File file = new File("/Users/mehran/Desktop/filee.txt"); 
     graph g = new graph(); 
     CreateGraph(file , g); 
     // System.out.println("ffff "+ g.getnode().get(0).getVertex()); 
     //g.printGraph(); 
     System.out.println("he : "+ g.getnode().get(1).getVertex()); 
     System.out.println("hey : " + g.getnode().get(1).getChild().get(1).getVertex()); 
     bfs(g.getnode().get(0)); 
    } 
} 

Мой графа .java код ниже:

import java.util.ArrayList; 
import java.util.List; 

public class graph { 

    public int count; // num of vertices 
    private ArrayList<node> vertices ; 

    public void printGraph() { 
     for(int i = 0; i < vertices.size(); i++) { 
      vertices.get(i).print(); 
     } 
    } 

    public graph() { 
     vertices = new ArrayList<node>(); 
     count = 0; 
    } 

    public void addnode(node n) { 
     ((List) vertices).add(n); 
    } 

    public ArrayList<node> getnode() { 
     return vertices; 
    } 

    public node FindNode(Integer V) { 
     for(int i=0; i < vertices.size() ; i++) { 
      if(vertices.get(i).getVertex() == V) 
       return vertices.get(i).getNode(); 
     } 
     return null; 
    } 

    public boolean InGraph(Integer V) { 
     for(int i = 0; i < vertices.size(); i++) { 
     // System.out.println("i " + i); 
     if (vertices.get(i).getVertex() == V) 
      return true; 
     } 
     return false; 
    } 
} 

Мой узел код .java ниже:

import java.lang.Thread.State; 
import java.util.ArrayList; 

public class node { 

    public Integer length = 0; 
    public ArrayList<node> child; 
    public int childCount = 0; 
    private Integer vertex; 
    public state State; 

    public void print() { 
     System.out.println("V : " + vertex); 
     for(int i = 0 ; i < child.size(); i++) { 
      System.out.println("childs "); 
      System.out.println(child.get(i).getVertex()); 
      // System.out.println(child.get(i).state); 
     } 
    } 

    public node(Integer vertex) { 
     // state = false; 
     this.vertex = vertex; 
     child = new ArrayList<node>(); 
    } 

    public node getNode() { 
     return this; 
    } 

    public void addChildnode(node adj) { 
     // adj.state = false; 
     adj.State = state.Unvisited; 
     child.add(adj); 
    } 

    public ArrayList<node> getChild() { 
     return child; 
    } 

    public Integer getVertex() { 
     return vertex; 
    } 
} 

И мой код состояния .java ниже:

public enum state { 
    Unvisited,Visiting,Visited; 
} 

Я пытаюсь пересечь график, используя BFS. У меня есть этот график: 0 2, 0 3, 2 4, 1 3, 2 1 с 5 ребрами. когда я передаю вершину 0 в очередь функций bfs, просто добавьте 2 и 3 и не добавьте детей 2 и 3. Я не могу понять, почему эта функция bfs работает некорректно. Любая идея, пожалуйста?

+0

Я пытаюсь использовать государство для посещая вершины, но я не дал правильного ответа и петли для в BFS функционируют два раза повторяющимися только для моих детей вершины «0» и я не могу дать детям из '2' и '3' вершин, я действительно не знаю ПОЧЕМУ ?! –

ответ

1
public static void bfs(node root) { 
    //Since queue is a interface 
    Queue<node> queue = new LinkedList<node>(); 

    if(root == null) return; 


    //Adds to end of queue 
    queue.add(root); 
    Integer count = 0; 
    while(!queue.isEmpty()) { 
     count++; 
     System.out.println("count : " + count); 
     //removes from front of queue 
     node r = queue.remove(); 
     System.out.println(r.getVertex() + "\t"); 
     // System.out.println(r.getChild().get(0).getVertex() + "\t"); 
     // Visit child first before grandchild 
     for(node n: r.getChild()) { 
      System.out.println("n "+n.getVertex()); 
      if(n.State == state.Unvisited) { 
       queue.add(n); 
      } 
     } 
     r.State = state.Visited; 
    } 
} 
+1

, пожалуйста, объясните подробнее ... tnx –

+1

Для '0' вы добавляете' 2' и '3' и отмечаете свое состояние как' true'. Когда вы перейдете к '2', поскольку' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ', вы не будете добавлять' Следовательно, отметьте его 'state' как' true' только после добавления всех дочерних узлов. –

+0

oh да спасибо u очень много. можете ли вы привести мне пример использования состояния в моем коде? , Я не знаком с этим. –

Смежные вопросы