You are given a non-negative integer n representing a 2n x 2n grid. You must fill the grid with integers from 0 to 22n - 1 to make it special. A grid is special if it satisfies all the following conditions:
All numbers in the top-right quadrant are smaller than those in the bottom-right quadrant.
All numbers in the bottom-right quadrant are smaller than those in the bottom-left quadrant.
All numbers in the bottom-left quadrant are smaller than those in the top-left quadrant.
Input: n =2Output: [[15,12,3,0],[14,13,2,1],[11,8,7,4],[10,9,6,5]]Explanation:
The numbers in each quadrant are:
Top-right: 3, 0, 2, 1
Bottom-right: 7, 4, 6, 5
Bottom-left: 11, 8, 10, 9
Top-left: 15, 12, 14, 13
max(3, 0, 2, 1) < min(7, 4, 6, 5)
max(7, 4, 6, 5) < min(11, 8, 10, 9)
max(11, 8, 10, 9) < min(15, 12, 14, 13)
This satisfies the first three requirements. Additionally, each quadrant is
also a special grid. Thus, this is a special grid.
The problem is recursive: each quadrant must itself be a special grid. We can fill the grid by recursively filling each quadrant with a range of numbers, ensuring the required order between quadrants. For a 2^n x 2^n grid, we split it into four quadrants, fill each recursively, and assign number ranges so that the top-right < bottom-right < bottom-left < top-left.
classSolution {
funspecialGrid(n: Int): Array<IntArray> {
funconstruct(n: Int, start: Int): Array<IntArray> {
val sz = 1 shl n
if (n ==0) return arrayOf(intArrayOf(start))
val len = sz / 2val block = len * len
val tr = construct(n-1, start)
val br = construct(n-1, start+block)
val bl = construct(n-1, start+2*block)
val tl = construct(n-1, start+3*block)
val ans = Array(sz) { IntArray(sz) }
for (i in0 until len) for (j in0 until len) {
ans[i][j+len] = tr[i][j]
ans[i+len][j+len] = br[i][j]
ans[i+len][j] = bl[i][j]
ans[i][j] = tl[i][j]
}
return ans
}
return construct(n, 0)
}
}