Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select adjacent fields with same values in two-dimentional array

I've got a two-dimmentional array filled with some data. I want to select all the fields with the same value as field [0][0] that are connected to it in a way presented on the image below:

highlighted fields

Example of matrix with fields I want to select highlighted in green (selected fields are adjacent to each other by at least one of four sides (N,W,S,E):

Can you think of some easy algorythm that will achieve that? I don't hope for some ready to use code - more like some guidelines.

like image 557
zorza Avatar asked Oct 22 '22 10:10

zorza


1 Answers

Use a recursive algorithm. Check each of the adjacent cells, and if it matches recurse with that cell being the starting point. Collect all the matching cells in a list. To avoid infinite loops, check whether the cell is already in the result list before recursing.

like image 137
Barmar Avatar answered Oct 24 '22 04:10

Barmar