Php 使用DFS查找两个节点之间的所有路径

Php 使用DFS查找两个节点之间的所有路径,php,graph,nodes,depth-first-search,Php,Graph,Nodes,Depth First Search,在过去的几天里,我一直试图找到一种方法来计算两个节点之间的所有非循环路径。我一直在进行广度优先搜索和深度优先搜索。我相当肯定两人都能完成这项任务。然而,我一直在努力研究如何调整下面的DFS代码,以找到两个节点之间所有可能的路径。我尝试了几种不同的方法来记住数组中的节点,递归,但我没有正确地实现它们,也没有能够输出可能的路径 最后,我想返回一个数组数组,其中包含两个选定节点之间的所有可能路径。有什么简单的修改我可以做到这一点吗?下面的代码是我目前正在使用的代码 function init(&

在过去的几天里,我一直试图找到一种方法来计算两个节点之间的所有非循环路径。我一直在进行广度优先搜索和深度优先搜索。我相当肯定两人都能完成这项任务。然而,我一直在努力研究如何调整下面的DFS代码,以找到两个节点之间所有可能的路径。我尝试了几种不同的方法来记住数组中的节点,递归,但我没有正确地实现它们,也没有能够输出可能的路径

最后,我想返回一个数组数组,其中包含两个选定节点之间的所有可能路径。有什么简单的修改我可以做到这一点吗?下面的代码是我目前正在使用的代码

function init(&$visited, &$graph){
  foreach ($graph as $key => $vertex) {
    $visited[$key] = 0;
  }
}

/* DFS args
$graph = Node x Node sociomatrix
$start = starting node
$end = target node (currently not used)
$visited = list of visited nodes
$list = hold keys' corresponding node values, for printing path;
*/

function depth_first(&$graph, $start, $end, $visited, $list){

  // create an empty stack
  $s = array();

  // put the starting node on the stack
  array_push($s, $start);

  // note that we visited the start node
  $visited[$start] = 1;

  // do the following while there are items on the stack
  while (count($s)) {

    // remove the last item from the stack
    $t = array_pop($s);

    // move through all connections
    foreach ($graph[$t] as $key => $vertex) {

      // if node hasn't been visited and there's a connection
      if (!$visited[$key] && $vertex == 1) {

        // note that we visited this node
        $visited[$key] = 1;

        // push key onto stack
        array_push($s, $key);

        // print the node we're at              
        echo $list[$key];                   
      }             
    }           
  }
}

// example usage
$visited = array();
$visited = init($visited, $sym_sociomatrix);
breadth_first($sym_sociomatrix, 1, 3, $visited, $list);

假设您有一个框架/库来创建一个图形数据结构并遍历它,您可以进行回溯深度优先搜索,如果您得到一个循环,则可以提前返回。如果存储起始节点的路径,则循环检测很容易。在C风格的伪代码中,抱歉,我不知道PHP,或者它是否能够递归:

void DFS(Vertex current, Vertex goal, List<Vertex> path) {
  // avoid cycles
  if (contains(path, current)
     return;

  // got it!
  if (current == goal)) {
     print(path);
     return;
  }

  // keep looking
  children = successors(current); // optionally sorted from low to high cost
  for(child: children)          
      DFS(child, add_path(path, child));      
}
然后你可以称之为开始,目标,倾听