How can I find suitable clusters in a grid of cubes of different colors?

Cluster definition

Any group of cubes of the same color, touching the planes of the face, not their angles.

The cluster would form a solid geometric shape.

To visualize the problem

Suppose each of these Legos has 1x1 units large.

legos

In a simplified code example, consider a 2x2x2 grid of 2x2x2 cubes:

 var mesh = [ // First layer ( x, y, z ) new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 1, 0, 1 ) //Second layer ( x, y, z ) new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 1 ), new THREE.Vector3( 1, 1, 0 ), new THREE.Vector3( 1, 1, 1 ) ]; 

enter image description here

Each cube in the grid has a color:

 //Indexes of mesh array sorted by color var colors = { red: [0, 1, 4, 6], green: [2, 3, 5, 7] } 
+5
source share
1 answer

This can be resolved with the fill fill . The Wikipedia page is instructive for two dimensions:

 Flood-fill (node, target-color, replacement-color): 1. If target-color is equal to replacement-color, return. 2. If the color of node is not equal to target-color, return. 3. Set the color of node to replacement-color. 4. Perform Flood-fill (one step to the south of node, target-color, replacement-color). Perform Flood-fill (one step to the north of node, target-color, replacement-color). Perform Flood-fill (one step to the west of node, target-color, replacement-color). Perform Flood-fill (one step to the east of node, target-color, replacement-color). 5. Return. 

You can expand this to three dimensions, noting that two cells are adjacent if their distance is 1 or more is simple, if they differ by one in one dimension, so you can iterate over all six neighbors instead of four for two sizes.

+3
source

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


All Articles