简体   繁体   中英

Determining all values that are equal & next to one another in a 2D array

I'm new to stackoverflow as well as programming so pardon me if I ask this question poorly.

So say I have a 2-D array with integer values from 1 through 4. It might look something like this:

3 3 3 1 3 1 3 1 2 1
1 3 1 3 3 1 1 1 1 1
1 4 3 3 1 3 3 4 3 4
1 4 1 1 3 3 1 4 2 4
1 1 1 4 1 3 3 1 1 3
1 2 3 3 3 3 3 3 1 1
4 1 4 3 3 2 1 1 4 1
1 3 3 3 4 1 4 2 2 3

Let me rewrite it so that I can isolate a part of the array I want us to observe:

x x x x x x x x x x
x x x x x x x x x x
x x x x x 3 3 x x x
x x x x 3 3 x x x x
x x x x x 3 3 x x x 
x x 3 3 3 3 3 3 x x
x x x 3 3 x x x x x
x 3 3 3 x x x x x x

We see that the 3's shown here are not only all equal in value but also directly "next to" one another and are all "connected".

I have 4 methods that determine whether or not the space to the right, left, top, or bottom of a space in the array is equal to a given start position:

boolean isEqualRight(int row, int column) {
    return array[row][column] == array[row][column + 1];
}
boolean isEqualLeft(int row, int column) {
    return array[row][column] == array[row][column - 1];
}
boolean isEqualUp(int row, int column) {
    return array[row][column] == array[row - 1][column];
}
boolean isEqualDown(int row, int column) {
    return array[row][column] == array[row + 1][column];
}

But, even if I know if a position in the array is equal and next to a start position, I can't think of a solution to determine all of the positions in the array that are equal and connected to the start.

I tried developing a loop that would cycle through a space next to a starting 3, determine if it is next and equal to it, and if so then do the same for the 3 that is next to it, and so on, and so on. But I faced an issue when the 3's started branching. Any thoughts?

This is a standard problem in computer graphics. The algorithm is called Flood Fill and is covered in detail in Wikipedia .

There are also many Java implementations out there if you wanted to study one (just google).

Your methods seem correct but you should add come code to catch any possible IndexOutOfBoundErrors. For example if you take the first element in your array and check up or left you will get an IndexOutOfBound Error as it will reference an element that does not exist, this goes for all boundary elements. This will prevent your code from running efficiently.

Just something to always consider when dealing with arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM