PHP implements graph based depth first traversal output 1 2 3... n's full permutation function

  • 2021-08-12 02:24:12
  • OfStack

In this paper, an example is given to show that PHP realizes the full arrangement function of depth-first traversal output 1, 2, 3... n based on graph. Share it for your reference, as follows:


<?php
$n=$_REQUEST["n"];
if($n>8)
{
  echo "{$n} Too big, affecting server performance ";
  return;
}
define("N",$n);
$d=array();
$v=array();
for($i=0;$i<=N;$i++){
  $d[$i]=$v[$i]=0;
}
function dfs($depth){
  global $d,$v;
  if($depth>=N){
    for($i=0;$i!=N;$i++){
      echo $d[$i];
    }
    echo "<br>";
    return;
  }
  for($i=1;$i<=N;$i++){
    if($v[$i]==0){
      $v[$i]=1;
      $d[$depth]=$i;
      dfs($depth+1);
      $v[$i]=0;
    }
  }
}
dfs(0);

Here, take the parameter n=4 passed in by get method as an example, and the output is as follows:


1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: