我正在制作一个照片马赛克应用程序,一个简单的解决方案是扫描位图以将位图分割成小方 block 并用小图像替换每个小方 block 。但是为了提高生成图像的质量,我想从中心而不是从左上角扫描位图。有没有现有的算法来解决这个问题?
例如:
在传统方法中,我们从左上角开始扫描二维数组:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
但我想从中心扫描到边界,呈螺旋状:
16 15 14 13
5 4 3 12
6 1 2 11
7 8 9 10
最佳答案
bool between(int x, int low, int high) {
return low <= x && x <= high;
}
// we use this constant array to help tweaking the (row,col) coordinate
const int D[4][2] = {
{0, 1}, // 0 - right
{1, 0}, // 1 - down
{0, -1}, // 2 - left
{-1, 0} // 3 - up
};
int a[n][n]; // suppose the array is n times n in size
int row = 0, col = 0, dir = 0; // initial direction is "0 - right"
for (int m = n*n; m >= 1; m--) {
a[row][col] = m;
int old_row = row, old_col = col; // remember current coordinate
row += D[dir][0];
col += D[dir][1];
if (!(between(row,0,n-1) && between(col,0,n-1))) { // have to move back
// move back
row = old_row;
col = old_col;
// change direction
dir++;
dir %= 4;
// move again
row += D[dir][0];
col += D[dir][1];
}
}
关于algorithm - 从中心扫描阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509489/