algorithm - 从中心扫描阵列

标签 algorithm

我正在制作一个照片马赛克应用程序,一个简单的解决方案是扫描位图以将位图分割成小方 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/

相关文章:

javascript - 在由不同颜色的立方体组成的网格中,如何找到匹配的簇?

c# - 任意定界符/转义字符处理的最佳算法是什么?

sql - 如何将 "weights"添加到MySQL表中并根据这些选择随机值?

algorithm - 给定平面上的加权点,找到 U 方 block 的位置,使总封闭重量最大化

python - 如何在没有 itertools.combinations 的情况下在 Python 中生成列表的递增排列

C++将整数数组分成 block

javascript - 使用 Javascript 进行快速排序的大 O 问题

algorithm - 范围内的 squarefree 数字计数

PHP (OOP) - 从调用的函数中获取对象

algorithm - 树中的节点是否被视为其自己的祖先?