0

I have a 2-dimensional array, I want to check if there is any way from the top row to a specific element in the array.

The way means: that there is continuously connected 1 from top to the element.

I've implemented a function to solve it: I can check every single row starting from row 1, if these 2 rows are connected then register their connection points and continue else return false(no way).

For example, the first 3 rows connected by these 3 points.

My JS Implementation:

function isWay(arr, row, col) {
  let count =crate_Nd_Array(arr.length);

  if (arr[row][col] == 0) {
      return false;
  }

  if (arr[row][col] == 1) {
     for(let i=1; i<arr.length; i++){
        for(let j=0; j<=col; j++){
           if(isOpen(arr,i,j)){  //is open check if the element is 1 or 0
             if(is_2_rows_connected(arr, i , j)){
  //is_2_rows_connected checks if there is a way between each 2 stacked rows.
                  let countt = count[i-1];
                  countt.push([[i,j], [i-1, j]])
             };
           }
        }
     }
  }

   return count;
}

/**is_2_rows_connected checks if there is a way between every 2 stacked rows. */

function is_2_rows_connected(arr, r, c)
{
  if(isOpen(arr,r,c) && isOpen(arr, r-1, c ))
  {   //isopen returns if T if 1 or 0
         return true;
  }

  return false;
}

Now, I can get the connection points between every stacked rows, but I'm stuck here.

It can be solved with union-find algorithm, but I don't know how to initialize it. any help please ??

matthias_h
  • 11,356
  • 9
  • 22
  • 40
Ahmad Ali
  • 704
  • 1
  • 10
  • 28
  • You only want to allow connection from the top row? What happens in a case where you have more than 1 columns with connections of 1 going down? ... refer to your first photo of the array. Do you register both columns? – Mosia Thabo Apr 26 '20 at 02:09
  • what's your expected return from your function? in your code you are returning an array of connected points, but in your question description it seems you are check if there is a way to a specific point from top row, so return a boolean value? – Colin Apr 26 '20 at 02:31
  • so basically, if there is a connection between every stacked rows, then you need to check if the number of connections = number of rows from top to the element, this is a true. else false – Ahmad Ali Apr 26 '20 at 03:53

1 Answers1

1

You can start from the target cell position and do a standard BFS/DFS pass to visit all reachable cells in the grid. If you reach the top row during this return true and if at then end no top row element has been reached return false.

Another way to do this would be starting from top row. For this, initially add all top row cells with 1 to queue/stack. From there check if the target cell is reachable using standard BFS/DFS.

xashru
  • 3,400
  • 2
  • 17
  • 30