I’m making a word game. The board is represented as a 2D C array. A simplified version of my populated array might look something like this.
[x][x][0][0][0][0][0] [x][0][0][0][x][0][0] [x][0][0][x][x][x][x] [0][0][0][0][x][0][0]
There are no diagonal connections between x blocks, only up, down, left and right.
I want an algorithm to check if there are two non-contiguous ‘blocks’ of X values. This algorithm, given a particular 2D game array, will enable me to decide between:
- Yes, there is only one contiguous block of Xs
- No, there is more than one contiguous block of Xs
For the example shown above, I would find ‘No’, because there is more than one contiguous block of Xs.
My first simple idea is to find one contiguous block of Xs and catalogue those values. It is easy for me to get a starting point in the middle of a contiguous block, for reasons that aren’t important to this question. If I can find an X anywhere that is not in my catalogued list, I can return ‘No’, else, ‘Yes’. However, this strikes me as a pretty inefficient way of doing it.
I understand that I would need to touch every item of the 2D array to comprehensively rule out another contiguous block. I’m more interested in the quickest way of finding a ‘No’.
Because the array is pretty small, I could implement my idea without any real performance problems. However, I’m sure there is a more elegant way, and I thought this problem might interest some algorithm-loving part of the stack overflow hive mind.
This could also be described somewhere in another SO question or the internet at large. Maybe I just don’t know the right way to phrase the question. If you do, please enlighten me. Best solution also gets a free copy of the as-yet-to-be-completed iOS word game. 😀
Your array forms a graph, and you are asking if the graph has more than one connected component. The easiest way to do this is probably to copy the array, erase the first connected component you find, then look for another X. If you find one, there were more than one component to begin with.
Erasing is a nice application of graph search. For example, you could do it this way (in C):