Need help with an algorithm

Status
Not open for further replies.

Screndib

Ars Tribunus Militum
2,038
This is what's I'm working with
scrsht.gif


Internally, there is an array of type Block, which is a struct defined as so:

code:<HR>
Code:
struct Block
{
	BlockColor	color;
	bool		highlight;
	BlockState	state;
	int			stateTime;	//number of frames block has been in given state<P>	//Constructor
	Block( void ) :color(EMPTY), highlight(false), state(BS_EMPTY), stateTime(0) {}
};

What I want to do is find groups of similarly colored blocks that have four or more of them touching. In the screen shot above the hilighted blocks would be what I'm looking for.

I'm pretty much stuck here for the time being, I don't have any good ideas on how to go about finding the adjacent blocks.

Anyone able to help?
 

Drommesyn

Smack-Fu Master, in training
87
So you're trying to perform a flood-fill operation. The bottom line is that flood-filling is a special case of finding the connected components of a graph. The standard way to achieve this is depth-first search; see, for instance, Sedgewick's book on algorithms, Chapter 29 if I recall.

The naive way to write the code is to consider the pixel grid as a graph in which each pixel is a single vertex, and in which two vertices are connected by an edge if (a) they are adjacent in the pixel grid, and (b) they are of the same colour. This technique is somewhat inefficient.

For a more efficient approach, consider the pixel grid as a graph structure in which vertices correspond to rows of pixels of a single colour.

For industrial-strength efficiency, you use the second graph, but you leave it in an implicit form, i.e. you compute the adjacency information for the graph 'on-the-fly', rather than creating an explicit graph object.

TEST CASE: make certain that you handle the case of a 'V' shape correctly - in other words, as you scan from top to bottom, it looks at first as if you have two separate components, but then they join up at the bottom.
 

Sdw

Ars Scholae Palatinae
1,444
I did a very similair thing for GLBlocks. I needed to find if four or more of the same blocks was connected. What I did was, much as you yourself had ocncluded, use a recursive approach. I started with the topmost block, flagged that one as visited, and then checked all directions, if I found a block of the same color that didn't have the 'visited-flag' set, I recursed to that one and so on.
 
Status
Not open for further replies.