0

I need to get all possible paths of a tree so I implemented a DFS like this:

void bisearch(std::vector<int> path, int steps,
                           int node, std::vector<std::vector<int>> *paths) {
  int sum = 0;
  if (path.size() == steps) {
    for(std::vector<int>::iterator it=path.begin(); it != path.end(); ++it) {
        sum += (*it);   
    }
    if (sum == node)
        paths->push_back(path);
  }
  else {
    std::vector<int> uPath(path);
    uPath.push_back(1);
    bisearch(uPath, steps, node, paths);
    std::vector<int> dPath(path);
    dPath.push_back(0);
    bisearch(dPath, steps, node, paths);
  }
}

The above code gives me all paths to some ending node for a tree of length "steps". I then loop through all ending nodes and run this to get every path. Issue is it takes forever! I was thinking of maybe hardcoding all the possible combinations to speed it up, of course I couldn't do this by hand since for instance a tree with 25 steps would have 2^25 ~= 35 million possible combinations, but maybe I could print the output from the search and use that to hardcode? Or does anyone see any easy optimizations I could make that would make a big difference on the performance? Thanks.

EDIT: Let me clarify a little. I need the path, that is the sequence of movements along the tree where 1 represents a right hand move and 0 a left (or up/down whichever you prefer). So for instance a 2 step tree I need the four ordered pairs (1,0) (0,1) (1,1) (0,0).

user2183336
  • 706
  • 8
  • 19

1 Answers1

1

Since "all the combinations" should mean just "the combinations of turning right / left at a certain level", you could just loop through 0 to 2 ^ n - 1, and the binary representation padded with 0 in the front might be just what you want.

If what you want is the count of paths with left turn count equals to a certain number k, then this just equals the numbers from 0 to 2 ^ n - 1 that has k bit equal to 1, and you could possibly use this to compute the result you want.

zw324
  • 26,764
  • 16
  • 85
  • 118
  • ok your answer of looping for 0 to 2^n-1 makes sense but how do you know how many 0s to pad for a given number? – user2183336 May 01 '13 at 15:03
  • Since all the numbers need to have n binary bits, just pad until the length is n, and note you'll have to pad the 0s at the front of the binary number, not the end. – zw324 May 01 '13 at 15:06
  • Ahh duh got it thanks a lot, I'll write that up and give it a spin and see if it helps the performance. – user2183336 May 01 '13 at 15:28
  • 1
    You can also use a [bitset](http://www.cplusplus.com/reference/bitset/bitset/) which will obviate the need to figure out how to pad your bitstring representation. The bitset is basically just a compacted vector that will hopefully reduce the cost of memory allocation and improve cache performance. – Zim-Zam O'Pootertoot May 01 '13 at 16:28