What's the fastest way to find deepest path in a 3D array?

后端 未结 4 2386
遇见更好的自我
遇见更好的自我 2021-02-14 15:34

I\'ve been trying to find solution to my problem for more than a week and I couldn\'t find out anything better than a milion iterations prog, so I think it\'s time to ask someon

4条回答
  •  没有蜡笔的小新
    2021-02-14 16:14

    I think you should be able to do it in O(N). When you parse your input, assign each node a 'caveNumber' initialized to 0. Set it to a valid number whenever you visit a cave:

    CaveCount = 0, IsolatedCaveCount=0
    AllSizes = new Vector.
    For each node, 
       ProcessNode(size:0,depth:0);
    
    ProcessNode(size,depth):
       If node.isCave and !node.caveNumber 
           if (size==0) ++CaveCount
           if (size==0 and depth!=0) IsolatedCaveCount++
           node.caveNumber = CaveCount
           AllSizes[CaveCount]++
           For each neighbor of node, 
                if (goingDeeper) depth++
                ProcessNode(size+1, depth).
    

    You will visit each node 7 times at worst case: once from the outer loop, and possibly once from each of its six neighbors. But you'll only work on each one once, since after that the caveNumber is set, and you ignore it.

    You can do the depth tracking by adding a depth parameter to the recursive ProcessNode call, and only incrementing it when visiting a lower neighbor.

提交回复
热议问题