This article mainly introduced the PHP implementation of the depth-first search algorithm (dfs,depth, first search), simple analysis of the depth-priority search algorithm principle and combined with specific examples of the implementation of PHP depth-first search for the specific steps and related operating skills, the need for friends can refer to the next
In this paper, the implementation of depth-first search algorithm in PHP is described. Share to everyone for your reference, as follows:
The implementation principle of depth-first search:
Implementation code:
<?phpclass search_method{ //non-graph array description private $dfs _save; Global record array private $arr; Control Branch- private $k = 0; Public function __construct () { $this->dfs_save = Array (Array ( 0,1,1,1,0,0,0,0,0), Array ( 1,0,0,0,1,0,0,0,0), Array (1,0,0,0,0,1,0,0,0), Array (1,0,0,0,0,0,1,0,0), Array (0,1,0,0,0,1,0,0,1 ), Array (0,0,1,0,1,0,0,1,0), Array (0,0,0,1,0,0,0,0,0), Array (0,0,0,0,0,1,0,0,0), Array ( 0,0,0,0,1,0,0,0,0), ); $this->arr = Array (); } Recursive implementation of depth-first search public function dfs ($v) { //Do some operations on vertices echo str_repeat ("-", $this->k); Echo ' V '. ($v + 1). ' <br> '; Record the visited vertex $this->arr[]= $v; Find vertices connected to vertices, continue depth first search for ($i =0; $i <9; $i + +) {if (!in_array ($i, $this->arr) &&$ if present this->dfs_save[$v] [$i]==1) { $this->k++; $this->dfs ($i); } } $this->k--; return;} }? >
To achieve the output result:
V1-V2--V5---V6----V3----V8---v9-v4--v7