I’m terribly sorry for the title, but describing my problem with a couple of words is a tad hard. I figured the rest of the post would explain it better! 😉
Description
I basically have a 2D array of tiles/objects/symbols and I want to split it up into two (or more) new 2D arrays whenever a group of tiles is separated by special tiles.
For example, if I have:
[x][x][0][0]
[0][0][x][0]
[0][0][x][0]
[0][0][0][x]
Where the symbol x is not wanted, then that should give me two new arrays:
[x][x][0][0]
[x][x][x][0]
[x][x][x][0]
[x][x][x][x]
and
[x][x][x][x]
[0][0][x][x]
[0][0][x][x]
[0][0][0][x]
One array for each group of interconnecting tiles.
In my specific case, I have null objects as x, and an arbitrary object for the rest. Basically, if I can’t reach tile B from tile A without crossing a null, then those two are two different groups.
I’ve played with it in my mind for a while, and the best I could come up with is surely far worse than O(n^2), given that they even worked in the first place. Flood fill springs to mind as something that could be used to find a group, but other than that, I’m not sure I can come up with any other similar problem to use in this instance.
The question
So what I’m asking is if you happen to know in which direction to take my problem and/or how to solve it. Computational complexity is not that very important since I plan not to execute this often nor on large arrays. Still, I hope i haven’t hit upon a NP-hard problem! :3
Thanks!
This is far from being a NP problem.
I will explain two different approaches to solve the problem. One will use a Flood Fill as you expected and the other a Disjoint-set data structure.
Flood Fill
Let’s say you have a matrix
N x Mwhere a position(row, column)isnullwhen is not used, it contains a value otherwise.You need to go through each column element
1..Mper row1..N. That’s very simple:You will need to call the Flood Fill algorithm each time you find a non-
nullvalue, the reason will become clearer after I will define the Flood Fill method below.You can modify this algorithm to mark each region with an specified number in a different array if you keep track of the number of regions recognized. You will notice I am using a queue instead of a recursive function, this will keep you away from hitting a maximum recursion bound limit.
Union-Find Algorithm
Another solution that I considered more expensive is using a Disjoint-set data structure to accomplish the same purpose. I will merely show the change to the
floodfillmethod.I hope this help.
I didn’t bother about showing the complexity since you didn’t care about it.