HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

PHP implementation of "depth-first search" on the graph data structure

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
depththegraphsearchphpfirststructureimplementationdata

Problem

As I am a totally self-taught 'person writing code', I decided to learn algorithms with one online course that taught them using Java for demonstrative purposes. The first topic I covered is the graph data structure and API.

I undertook to rewrite Java examples into PHP for training purposes. I would be really grateful if you could review this code and point to its biggest shortcoming.

It was not always possible to reproduce certain behaviours and data structure that are found in Java so I had to resort to some workarounds.

Here is the code with explanations:

/**
* Bag stores all vertices adjacent to a given vertex.
* It's here to imitate Java's 'Bag' data structure
*/
class Bag implements IteratorAggregate
{
    public $vs = array();

    public function getIterator()
    {
        return new ArrayIterator($this->vs);
    }
}


-

class Graph
{

    private $V;

    /* Adjacent vertices */
    private $adj = array();

    /**
    * @param int $V The total number of vertices in the graph
    */
    public function __construct($V)
    {
        $this->V = $V;
        for ($v = 0; $v adj[$v] = new Bag;
        }
    }

    /**
    * Throw all adjacent vertices of a given vertex into this vertex' Bag.
    * This will create 'edges' - connection between vertices.
    * 
    * @param int $v Vertex to connect
    * @param int $w Vertex to connect
    */
    public function addEdge($v, $w)
    {
        $this->adj[$v]->vs[] = $w;
        $this->adj[$w]->vs[] = $v;
    }

    /**
    * @return Bag All ajacent vertices of a given vertex
    */
    public function returnBag($v)
    {
        return $this->adj[$v];
    }

    public function returnAllVertices()
    {
        return $this->adj;
    }

}


-

```
class DepthFirstPath
{
private $marked = array();

/ This array stores parent-link representation of a tree rooted at $s (source) /
private $edgeTo = array();

private $s;

/**
* @param Graph $G An instance of the graph

Solution

It's totally unnecessary to have a Bag class if all you do is reach through to its only field.

Generally, all your classes should either have multiple fields or engage in some kind of non-trivial validation or data-hiding to justify the necessity for a class.

Context

StackExchange Code Review Q#86284, answer score: 2

Revisions (0)

No revisions yet.