V
V
vakavakvaka2015-11-06 14:51:56
Programming
vakavakvaka, 2015-11-06 14:51:56

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
6f0240550ed74fd8955ffb0433d2de15.png
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

4 answer(s)
S
Stanislav Makarov, 2015-11-06
@Nipheris

Depth first search

A
alexxandr, 2015-11-06
@alexxandr

modification of the wave algorithm: the wave passes through the necessary cells and selects them, on unnecessary cells it fades

D
Dmitry Makarov, 2015-11-06
@DmitryITWorksMakarov

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.

R
Roman Kitaev, 2015-11-06
@deliro

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 question

Ask a Question

731 491 924 answers to any question