Thien N Thien N -4 years ago 163
Javascript Question

How to separate clusters ( 4 direction connected components) in a 2D array?

for example, I have 2d array like this:

1 2 2 2 2 1 1 1 1 2 1 1
2 1 1 1 2 1 2 2 1 1 2 1
2 2 1 2 1 1 2 2 2 2 1 1
1 1 1 2 1 2 1 2 2 1 1 2
1 1 2 1 2 1 2 1 2 2 2 2
1 1 2 2 2 2 1 2 1 2 1 1
2 1 1 2 1 1 2 2 1 1 1 2


And I want to label the connected components (4 directions)to be like this:

1 2 2 2 2 3 3 3 3 4 5 5
6 7 7 7 2 3 8 8 3 3 9 5
6 6 7 10 3 3 8 8 8 8 5 5
7 7 7 10 3 11 12 8 8 5 5 8
7 7 13 14 13 15 16 17 8 8 8 8
7 7 13 13 13 13 18 19 20 8 20 20
21 7 7 13 22 22 19 19 20 20 20 23


the way to label the clusters is like the flood fill, if it connects to their neighbor by up-down-left-right direction, they will be grouping in the same cluster. we go from top left to bottom right.
Please help me solve this problem. Thanks!!!(javascript code example would be great)

Answer Source

First, change the value of 1 to -1, because you need to use 1 as flag.

Then you could iterate the elements and perform a check and if it has the flag -1, then change it to the actual value. Proceed with the element of the right and bottom.

If an element was found, increment value.

function test(array, i, j, value) {
    if (array[i] && array[i][j] === -1) {
        array[i][j] = value;
        test(array, i + 1, j, value);
        test(array, i, j + 1, value);
        return true;
    }
}

var data = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]],
    value = 1;

data.forEach(function (a) {
    a.forEach(function (b, i, bb) {
        bb[i] = -b;
    });
});

data.forEach(function (a, i, aa) {
    a.forEach(function (b, j, bb) {
        test(aa, i, j, value) && value++;
    });
});

document.getElementById('out').innerHTML = data.map(function (a) { return a.join(' '); }).join('\n');
<pre id="out"></pre>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download