我怎样才能重新排列物品移动在上面的依赖? [英] How can I rearrange array items moving dependencies on top?

查看:123
本文介绍了我怎样才能重新排列物品移动在上面的依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下的阵列上一个又一个,其中每个项目可能会(或可能不取决于):

I have the following array where each item may (or may not depend) on another one:

$test = array(
    'c' => array(
        'depends' => 'b'
    ),
    'a' => array(),
    'b' => array(
        'depends' => 'a'
    ),
    'd' => array(
        'depends' => 'a'
    ),
);

我想移动(或再拍阵列)是依赖移动顶部。首页 A ,然后 B D (都取决于 A ),最后 C 依赖于 B 。对 B 的顺序和 D 是无关紧要的:

I want to move (or make another array) with dependencies are moved at the top. First a, then b and d (both depend on a) and finally c which depends on b. The order of b and d is irrelevant:

$rearranged = array(
    'a' => array(),
    'b' => array(
        'depends' => 'a'
    ),
    'd' => array(
        'depends' => 'a'
    ),
    'c' => array(
        'depends' => 'b'
    ),
);

我是pretty的肯定,这是一个相当普遍的情况和之前的重新发明轮子并浪费时间。我想知道是否有任何数据结构可以做的工作对我来说。

I'm pretty sure that this is a quite common situation and before reinventing the wheel and waste time I'd like to know if there is any data structure that can do the job for me.

修改:忘了说,循环引用应检测( B 依赖于 A 依赖于 B 不应该被允许)。

EDIT: forgot to say that circular references should be detected (b depends on a that depends on b should not be allowed).

推荐答案

这就是所谓的拓扑排序。如果你认为你的结构图,其中一个依赖于B等于从顶点B A向边到顶点一个,你应该做一个拓扑排序,以得到答案。

This is called topological sorting. If you consider your structure as a graph, where "a depends on b" is equal to a directed edge from vertex b to vertex a, you should just do a topological sort to get your answer.

拓扑排序的实现可以这样做:

Implementation of topological sort can be done like this:

让图形[n]的[n]的是对应于你的阵列(曲线图[I] [j]的= 1表示Ĵ取决于i)该曲线图。

let graph[ n ][ n ] be the graph corresponding to your array (graph[ i ][ j ] = 1 means j depends on i).

  1. ANS 的= {} //空序列
  2. 收入 = 新阵列 [N]
  3. 收入的[I] =边缘入射的顶点数量我
  4. 使用 = 新阵列 [N] //表明,如果任何顶点已经被使用,默认全是假的
  5. ,而 ANS 的.size!= N //仍有未使用的顶点
    也开始
    查找 我ST 收入的[I] == 0和使用的[I] ==虚假
    ANS 的.append(我)
    每个ĴS.T。 的[I] [J] == 1 递减 收入的研究[J]
    结束
  6. 返回 ANS
  1. ans = {} // empty sequence
  2. income = new array[ n ]
  3. income[ i ] = number of edges incoming to vertex i
  4. used = new array[ n ] // shows if any vertex has already been used, default all false
  5. while ans.size != n // there are still unused vertexes
    do begin
    find i s.t. income[ i ] == 0 and used[ i ] == false
    ans.append( i )
    for each j s.t. graph[ i ][ j ] == 1 decrement income[ j ]
    end
  6. return ans

这篇关于我怎样才能重新排列物品移动在上面的依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆