How to do a topological sort from a subset of items from a given graph?

后端 未结 2 1483
谎友^
谎友^ 2021-01-24 12:52

I have the following problem: You are given a todo list, some items of which depend on others. Write a function that takes a subset of those todos and returns an ordered list of

相关标签:
2条回答
  • 2021-01-24 13:10

    Don't think of this as a topological sort. Think of this as "do dependencies first, do not do them twice." Which is simple recursive function as long as we keep track of what we will do, and what has been done.

    The following Python solution may make this clearer.

    def arrange_tasks(dependencies, todo, in_order=None, done=None):
        if in_order is None:
            in_order = []
        if done is None:
            done = set()
    
        for item in todo:
            # Do we need to?
            if item not in done:
                # Marking it done first avoids deep recursion on dependency loops!
                done.add(item)
                # Make sure that dependencies happened.
                arrange_tasks(dependencies, dependencies[item], in_order, done)
                # And now this can happen.
                in_order.append(item)
        return in_order
    
    print(arrange_tasks(
        {
            'make a sandwich': ['buy groceries'],
            'buy groceries': ['go to store'],
            'go to store': []
        },
        ['buy groceries']
    ))
    
    0 讨论(0)
  • 2021-01-24 13:19

    Instead of taking a separate filtering pass, you should be able to check each task for addition to the output filteredTasks as it is processed for addition to orderedTasks.

    Since the only other use of orderedTasks is to check its length, you should then be able to replace it with a counter.

    This might not make your function much faster, but it will simplify your code.

    0 讨论(0)
提交回复
热议问题