dongzhazhuo0572 2018-04-16 15:36
浏览 9
已采纳

Algo检测形成路径的节点的顺序

my problem is very simple, I'll try to explain with example. I have an array (unsorted) like so:

$nodes = [
  ['id' => 1, 'dest_id' => 2],
  ['id' => 2, 'dest_id' => 3],
  ['id' => 3, 'dest_id' => null],
  ['id' => 4, 'dest_id' => 5],
  ['id' => 5, 'dest_id' => null],
  ... etc
]

So basically nodes have an id and can have a destination which is the id of another node. Destination can be null. No node can have the same destination. I'm looking for an algorithm that could output this:

$paths = [[1, 2, 3], [4, 5]]

As you can see, in the output, the nodes that form a path are ordered so that node 2 which is destination of node 1 is placed after node 1.

Any help? Thank you.

  • 写回答

1条回答 默认 最新

  • doulei8861 2018-04-17 15:08
    关注

    So since there doesn't exist an answer to my question, I will answer it with what I came up with, in order to close it. But it is not a very good answer (sorry).

    $raw_nodes = [
      ['id' => 1, 'dest_id' => 2],
      ['id' => 2, 'dest_id' => 3],
      ['id' => 3, 'dest_id' => null],
      ['id' => 4, 'dest_id' => 5],
      ['id' => 5, 'dest_id' => null]
    ];
    
    $nodes = [];
    // get the nodes in such a way that you can access them from their id
    foreach($raw_nodes as $raw_node) {
      $nodes[$raw_node['id']] = [
        "id" => $raw_node['id'],
        "dest_id" => $raw_node['dest_id'],
        "parent_id" => null
      ];
    }
    
    // find the parent to each node
    foreach($nodes as $node) {
      if ($node['dest_id'] && $nodes[$node['dest_id']]) {
        $nodes[$node['dest_id']]['parent_id'] = $node['id'];
      }
    }
    
    function buildPath($nodes, $node) {
      $path = [];
      if ($node['parent_id']) {
        $path = buildPath($nodes, $nodes[$node['parent_id']]);
      }
      array_push($path, $node['id']);
      return $path;
    }
    
    $paths = [];
    // for every node without a destination,
    // build its full path by recursive search starting from its own parent
    foreach($nodes as $node) {
      if ($node['dest_id'] === null) {
        $path = buildPath($nodes, $node);
        array_push($paths, $path);
      }
    }
    

    Now $paths contains the output I want! Thanks everyone.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码