/** * @param Graph $g * @return boolean Whether the graph is connected */ public static function isConnected(Graph $g) { // the null graph and singleton graph are considered connected if ($g->order <= 1) { return true; } // empty graphs on n>=2 nodes are disconnected if ($g->empty) { return false; } $vertices = $g->getVertices(); $source = reset($vertices); $x0 = $source->label; if ($g->directed) { $undirectedG = new Graph(); foreach ($vertices as $vertex) { $undirectedG->addVertex($vertex->label); } foreach ($vertices as $vertex) { foreach ($vertex->getDiscoveryEdges() as $edge) { $undirectedG->getVertex($vertex->label)->addOutEdgeToId($edge->sink->label); } } $g = $undirectedG; } return count(self::dfs($g, $x0)) == $g->order; }