Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding adjacent elements in a 2d array and counting them.

Im stumped on what to do for this part of my homework and could really use some help. I need to cycle through a given 2d array and find all similar elements that are adjacent to another and count that so for example

AA--B
AA--B
-AA--
----C

So the count would be 3 one for the As one for the Bs and one for the C, I just kinda need an idea where to start So far i have

public static int howManyOrganisms(char[][] image){
    int count = 0;
    for (int i = 0; i < image.length; i++) {
        for (int j = 0; j < image[i].length; j++) {
            if(image[i][j] != '-') {
                count++;

            }
            System.out.println();
        }
        return howManyOrganisms(image, count);
    }
}

I need help figuring out how to track the total number of elements that are within contact of one another (so left, right, down, up) being another similar element.

like image 247
Forrest Walker Avatar asked Dec 31 '25 04:12

Forrest Walker


1 Answers

In each iteration, you can use your i,j variables to "navigate" the 2d plane and see if any interacting items are the same. In each iteration you would check the following indexes to see if they are the same:

  • image[i-1][j] (one row up)
  • image[i+1][j] (one row down)
  • image[i][j-1] (one left)
  • image[i][j+1] (one right)

Of course for all of these statements first you should check if +1/-1 is still within the size of your matrix, otherwise you will end up with out of bounds exception.

like image 106
peterxz Avatar answered Jan 01 '26 19:01

peterxz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!