0

我正在开发一个图形数据结构,但我遇到了一个问题:

<?php  
class Graph
{
    var $graph_arr = array();

    function Graph()
    {
        $this->graph_arr = array();
        //initialization of nodes, mythical for now
        $n = new Node("A", array("B", "C"));
        $this->graph_arr[] = $n;
        $n = new Node("B", array("A", "D"));
        $this->graph_arr[] = $n;
        $n = new Node("C", array("A", "E", "F"));
        $this->graph_arr[] =$n; 
        $n = new Node("D", array("B"));
        $this->graph_arr[] = $n;
        $n = new Node("E", array("C"));
        $this->graph_arr[] = $n;    
        $n = new Node("F", array("C"));
        $this->graph_arr[] = $n;
    }
};

class Node
{
    var $node_name;
    var $adjacent_nodes;
    var $is_visited;

    function Node($node_name, $adjacent_nodes)
    {
        $this->node_name = $node_name;
        $this->adjacent_nodes = $adjacent_nodes;
    }
    /** returns array of adjacent nodes **/

    function getAdjacentNodes()
    {
        return $this->adjacent_nodes;
    }

    function getNodeName()
    {
        return $this->node_name;
    }

    function isVisited()
    {
        return $this->is_visited;
    }

    function setVisited()
    {
        $this->is_visited = true;
    }
};

?>

好吧,当我创建 Graph 对象时,数组的大小为 0。我无法添加新节点。

4

1 回答 1

1

尝试像这样更改您的 Graph 类:

class Graph
{
  var $graph_arr = array();

  function __construct() {
     $this->graph_arr = array();

   //initialization of nodes, mythical for now
   $n = new Node("A", array("B", "C"));
   $this->graph_arr[] = $n;
   $n = new Node("B", array("A", "D"));
   $this->graph_arr[] = $n;
   $n = new Node("C", array("A", "E", "F"));
   $this->graph_arr[] =$n; 
   $n = new Node("D", array("B"));
   $this->graph_arr[] = $n;
   $n = new Node("E", array("C"));
   $this->graph_arr[] = $n;    
   $n = new Node("F", array("C"));
   $this->graph_arr[] = $n;   
 }
}  
于 2012-11-25T14:47:08.813 回答