我希望你能帮助我理解这个转换过程。我想要将一个二维NxN矩阵递归地转换成其z-order版本。
例如,给定数组:
[ 1 2 ]
[ 3 4 ]
Z-order是指元素在屏幕上的叠放顺序。
[ 1 2 3 4]
z-order转换的递归步骤是什么?
我希望你能帮助我理解这个转换过程。我想要将一个二维NxN矩阵递归地转换成其z-order版本。
例如,给定数组:
[ 1 2 ]
[ 3 4 ]
[ 1 2 3 4]
z-order转换的递归步骤是什么?
递归方式很简单:
代码实现:
#include <iostream>
template<typename M, typename CBACK>
void zorder(const M& m, int y0, int x0, int size,
CBACK cback)
{
if (size == 1) {
// Base case, just one cell
cback(m[y0][x0]);
} else {
// Recurse in Z-order
int h = size/2;
zorder(m, y0, x0, h, cback); // top-left
zorder(m, y0, x0+h, h, cback); // top-right
zorder(m, y0+h, x0, h, cback); // bottom-left
zorder(m, y0+h, x0+h, h, cback); // bottom-right
}
}
void print(int x) {
std::cout << x << " ";
}
int main(int argc, const char *argv[]) {
int x[][4] = {{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16}};
zorder(x, 0, 0, 4, print);
std::cout << std::endl;
return 0;
}
1 2 5 6 3 4 7 8 9 10 13 14 11 12 15 16
int zorder_x_of(int index) {
int x = 0;
for (int b=0,k=0; (1<<b) <= index; b+=2,k++) {
x += ((index & (1<<b)) != 0) << k;
}
return x;
}
int zorder_y_of(int index) {
return zorder_x_of(index>>1);
}
template<typename M, typename CBACK>
void zorder2(const M& m, int size, CBACK cback)
{
for (int i=0; i<size*size; i++) {
cback(m[zorder_y_of(i)][zorder_x_of(i)]);
}
}
cback
参数上添加了解释,但是当然一个单独的SO答案并不是解释C++模板元编程的正确场所。如果你对此一无所知,我建议你在这个主题上进行一些调查,因为在某些情况下,模板可以成为强大的武器。但请注意,存在严重的风险,即被卷入滥用模板的极端情况,甚至像boost.spirit这样的荒谬工具也会显得合理。 - 6502NxM
,其中 N
是列数,M
是行数。int arr[2][2] = {{2,4},{3,5}};
for (int i=0; i<2 * 2; ++i){
std::cout << *(&arr[0][0] + i); // or *(arr + i)
}