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 ??