How to select adjacent fields with the same values ​​in a two-dimensional array

I have a two-dimensional array filled with some data. I want to select all the fields with the same value as the field [0] [0], which are connected to it by the method shown in the image below:

highlighted fields

An example of a matrix with fields I want to highlight the ones highlighted in green (the selected fields are adjacent to each other, at least on one of the four sides (N, W, S, E):

Can you come up with some simple algorithm that will achieve this? I do not hope that some are ready to use the code - more like some recommendations.

+4
source share
3 answers

Use a recursive algorithm. Check each of the neighboring cells, and if it matches recursion, when this cell is the starting point. Collect all the relevant cells in the list. To avoid endless loops, check if the cell is in the list of results before recursion.

+3
source

Hm, something like this, maybe ...?

Set match to content (0,0). Create an open list and a closed list. Press (0,0) on open .

While open contains elements: {place the element off open and push closed . Look at all the adjacent slots for this element in the matrix and for each adjacent slot whose contents are equal to match : {take the coordinates of this slot and if the coordinates are not in closed or open , then click on open . }}

After execution, closed must contain the desired list of coordinates.

0
source

Thanks to your advice, I came up with this solution:

  function findAdjacent(matrix){ var x= 0,y=0; //starting point return check(x,y,matrix); } function check(x,y,matrix){//where the recursive magic happens if(matrix[x][y]==1){ checked[x][y]="1"; if(x-1>=0 && matrix[x-1][y]==1 && checked[x-1][y]!=1){ check(x-1,y,matrix); } if( y-1>=0 && matrix[x][y-1]==1 && checked[x][y-1]!=1){ check(x,y-1,matrix); } if(x+1<matrix.length && matrix[x+1][y]==1 && checked[x+1][y]!=1){ check(x+1,y,matrix); } if(y+1<matrix.length && matrix[x][y+1]==1 && checked[x][y+1]!=1){ check(x,y+1,matrix); } } return checked; } var startingMatrix = []; startingMatrix[0] = [1,2,3,4,5,6,7,1]; startingMatrix[1] = [1,1,3,4,1,6,1,1]; startingMatrix[2] = [1,1,1,1,1,1,7,1]; startingMatrix[3] = [5,1,1,1,5,1,7,1]; startingMatrix[4] = [5,2,3,4,1,1,7,1]; startingMatrix[5] = [1,2,1,4,5,1,1,1]; startingMatrix[6] = [1,1,1,1,1,1,0,1]; startingMatrix[7] = [1,1,3,4,4,1,3,1]; var checked=[]; //empty matrix for marking up checked files checked[0] = [0,0,0,0,0,0,0,0]; checked[1] = [0,0,0,0,0,0,0,0]; checked[2] = [0,0,0,0,0,0,0,0]; checked[3] = [0,0,0,0,0,0,0,0]; checked[4] = [0,0,0,0,0,0,0,0]; checked[5] = [0,0,0,0,0,0,0,0]; checked[6] = [0,0,0,0,0,0,0,0]; checked[7] = [0,0,0,0,0,0,0,0]; (function() { document.write("<br>"); findAdjacent(startingMatrix); })(); 

Everything seems to be working fine. But of course, there is some way to improve this code, right?

0
source

Source: https://habr.com/ru/post/1479185/


All Articles