So I have an assignment where I have to recreate a 3d chessboard that is a RxC grid of squares each being a different height. If the chessboard is water tight, and someone pours
This is a bit brute-force-ish but would probably work.
You might try to conceptually break the board into layers for instance:
-------------------------
0 | 1 | 1 | 0 | 1 | 1 | 0
1 | 0 |-1 | 1 | 0 | 0 | 1
1 | 1 | 1 | 1 | 1 | 1 | 1
-------------------------
Looking at just the lowest layer. Assuming -1 is the bottom, the board would look like this:
-------------------------
0 | 0 | 0 | 0 | 0 | 0 | 0
0 | 0 |-1 | 0 | 0 | 0 | 0
0 | 0 | 0 | 0 | 0 | 0 | 0
-------------------------
For each square, determine if there exists a square to the left, right, top and bottom that all have a greater value. In this case we count 1.
Then move to the next layer, filling in the "holes" in the last layer.
-------------------------
0 | 1 | 1 | 0 | 1 | 1 | 0
1 | 0 | 0 | 1 | 0 | 0 | 1
1 | 1 | 1 | 1 | 1 | 1 | 1
-------------------------
Rinse, repeat. In this layer we count 4 giving us a total of 5.
-------------------------
1 | 1 | 1 | 1 | 1 | 1 | 1
1 | 1 | 1 | 1 | 1 | 1 | 1
1 | 1 | 1 | 1 | 1 | 1 | 1
-------------------------
Top layer obviously has none and we're done.
In pseudo code:
for each layer l in layers
for each square in l
if there exists a square left, right, top and bottom with higher value
count the square.
Edit
Of course since there is something seriously wrong with me, when I woke up this morning the first thing I thought of was this problem and immediately broke my solution.
Let's make one change to the example:
-------------------------
0 | 1 | 1 | 0 | 1 | 1 | 0
1 | 0 |-1 | 1 | 0 | 0 | 1
1 | 1 | 1 | 1 | 1 | 0 | 1
-------------------------
^
Open a hole to the outside. With the current algorithm we would get a solution of 4 which is obviously wrong.
To fix this we need to implement a back tracking algorithm.
Instead of looking anywhere to the left, right, top and bottom for a higher value, we check just the immediately adjacent squares. If any are at the same height we need to visit that square as well and perform the check again. If we find our way to the outside then the original square (and subsequently all the visited squares) fail. If we hit a dead end, then all the visited squares can be counted.
With this modification we would get the correct result of 3.