Answer the question
In order to leave comments, you need to log in
How to find all neighboring cells of the same type in a two-dimensional array?
Hello!
Given a two-dimensional array like this one: It is
necessary to search for all adjacent cells of the same color, for example, if the user selects cell number 1 in the figure, then the algorithm should select all cells circled in black, if 2, then all circled in yellow.
Tell me, please, in which direction to dig?
Thank you!
Answer the question
In order to leave comments, you need to log in
modification of the wave algorithm: the wave passes through the necessary cells and selects them, on unnecessary cells it fades
Imagine that a two-dimensional array is a graph, where each cell is a node. Node data: its coordinates, color, array of links to neighbors, Boolean value visited/not visited.
Mark all nodes as unvisited.
The node of the graph is fed to the input of the algorithm.
Procedure P:
1. Give the coordinates of the input node.
2. Mark the input node visited.
3. Apply procedure P to all unvisited neighbors of the same color.
It is not necessary to construct the graph explicitly. You can get neighbors directly in the P procedure. For "visited / not visited" you need some kind of fast and compact data structure in which you can quickly write cell coordinates and quickly check whether any coordinates were recorded before.
In the simplest case, this is a two-dimensional Boolean array of the same size as the original one. But depending on the source data and constraints, other methods may be more appropriate.
Like this
I don’t know if the python is familiar, but you can understand the essence. All the salt is in the find method.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question