Problems with an Array Algorithm

I have a 2D of integers size expressed as theGridX and **theGridY" in size each cell contains a number between 1 and 5. There is then a function the will set various cells to ZERO based on a predetermine algorithm. This part works just fine.

Once the desired cells are set to zero, Another function is supposed to collapse each column so that the “zeros” float to the top of the column

Here is the function I have… the problem is sometimes it works perfectly, other times it leaves the bottom most “zero” alone, not collasping the entire column

Does anyone see the flaw?

 // adjust the board rows (bottom up)
        for y in(0...theGRIDY-1).reversed() {
            for x in(0...theGRIDX-1) {
                if sgBoard[x,y] != 0 { continue }
                if y>0 {
                    for z in(1...y).reversed() {
                        sgBoard[x,z]=sgBoard[x,z-1] // move the cell above the zero down
                        sgBoard[x,z-1]=0
                    }
                }
            }
        }

If you have two 0’s above each other, they just switch place, then when you get to the >0 above those 2 0’s you don’t move the number to the bottom of the column of 0’s.

There’s smarter ways to do this but its just a quick example and as the data is so small it doesn’t matter. Drop this into window.open and check the debug window.

Dim sgBoard(9, 9) As Integer

For x As Integer = 0 To 9
  For y As Integer = 0 To 9
    sgBoard(x, y) = System.Random.InRange(0, 5)
  Next
Next

sgBoard(0, 7) = 1
sgBoard(0, 8) = 0
sgBoard(0, 9) = 0

'DisplayArray(sgBoard())
For y As Integer = 0 To 9
  Dim r As String = ""
  For x As Integer = 0 To 9
    r = r + sgBoard(x, y).ToString + " "
  Next
  System.DebugLog(r)
Next
'--

For x As Integer = 0 To 9
  For r As Integer = 1 To 9 'make sure we do it enough times to get a 0 from the bottom to the top
    For y As Integer = 9 To 1 Step -1
      If sgBoard(x, y) = 0 Then
        sgBoard(x, y) = sgBoard(x, y - 1)
        sgBoard(x, y - 1) = 0
      End If
    Next
  Next
Next

system.DebugLog(" ")

'DisplayArray(sgBoard())
For y As Integer = 0 To 9
  Dim r As String = ""
  For x As Integer = 0 To 9
    r = r + sgBoard(x, y).ToString + " "
  Next
  System.DebugLog(r)
Next
'--

the attempt above started at the bottom of the array and attempted to pull things down.
What needed to be done was start at the top and PUSH things down

    for x in(0...theGRIDX-1) {
            for y in(0...theGRIDY-2) {
                if sgBoard[x,y+1] == 0 {
                        for z in(0...y).reversed() {
                            sgBoard[x,z+1]=sgBoard[x,z]
                            sgBoard[x,z]=0
                        }
                }
            }
        }