Search code examples
javascriptarraystraversaldepth-first-searchbreadth-first-search

How can I find all paths in 2D array?


I am trying to write javascript that will map all the unique paths from root to leaf, each node can connect to the adjacent node on the next line. For example the root can connect to next row as 4,2 or 4,4. A unique path the the leaf would be 4,2,4,2,1

             4
            2 4
           6 4 2
          7 4 2 1
         9 4 2 1 4

I was able to convert the triangle into a 2D array that is structured like this.

a[0] = [4]
a[1] = [2,4]
a[2] = [6,4,2]
a[3] = [7,4,2,1]
a[4] = [9,4,2,1,4]

I want to find all the paths from root to leaf such as

4,2,6,7,9
4,2,6,7,4
4,2,6,4,4

I'm new to Depth First Search and Breadth first search. Could this be achieved with those algorithms?


Solution

  • Since you are looking for all the paths, this is a school example for simple recursion:

    var a = [];
    a[0] = [4];
    a[1] = [2,4];
    a[2] = [6,4,2];
    a[3] = [7,4,2,1];
    a[4] = [9,4,2,1,4];
    
    function r(s, v, h) { // string, vertical, horizontal
      s = s + a[v][h];
      if (v>3) {
        console.log(s);
      } else {
        r(s, v+1, h);
        r(s, v+1, h+1);
      }
    }
    console.log('-----------------')
    r('', 0, 0);