2017-04-10 70 views
-1
/*for example using a graph of this nature 
        ----1-----0 
        /\ 
       ---2----3----1 
        /\ /\ 
       --4--5--6--7---2 

     at level 2 it will return 1,2,4,5,3 instead of 1,2,4,5,3,6,7 

this is the main function to loop through the graph*/ 
public function set_data() 
{ 
    $this->data_type(); 
    while(count($this->_open) > 0 && $this->_state !== 'success') 
    { 
     $depth = $this->_depth; 
     $current = array_pop($this->_open); 

     if($current == $this->_goal){ 
      $this->_state = 'success'; 
     } 
     if ($depth < $this->_limit) { 
      $this->set_children($current, $depth); 
     } 
     else{ 
      $this->_state = 'cutoff'; 
     } 
     array_push($this->_close, $current); 
    } 
} 
// the function to generate the children 
public function set_children($current, $depth) 
{ 
    if(isset($this->_graph["$current"])){ 
     foreach ($this->_graph["$current"] as $value) 
     { 
      //implementing stack - LIFO 
      array_push($this->_open, array_pop($this->_graph["$current"])); 
     } 
     $depth = $depth+1; 
     $this->_depth = $depth; 
    } 
} 
+0

thanks @ miken32 – Tunde

回答

0

過了很久,我終於找到了解決辦法。我將$ depth作爲數組來保存相應節點的深度。

  • 首先初始化

    $這 - > _深度= [0];

  • 其次,當前節點的當前深度

    $深度= array_pop($這 - > _深度);

  • 三,建立深度每個子節點

    array_push($本 - > _深度,$深度++); $ depth--;