c - 在矩阵中查找正方形

标签 c algorithm matrix multidimensional-array

我无法想出一种算法来遍历由 0 和 1 组成的矩阵,例如看起来像这样:

3 5
1 0 1 1 1
0 0 1 0 1
0 0 1 1 1

前两位数字是行数和列数。零是空白,零是实际的“线”。我知道要遍历矩阵,我需要使用两个这样的嵌套循环:

for(int i = 0; i < rows; i++)
    for(int j = 0; j < cols; j++)
        /* code */

我需要能够将正方形的左上角坐标和右下角坐标保存在矩阵中。

我将矩阵以及行数和列数保存在一维字段中。如果打印到屏幕上,这个特定的矩阵看起来像这样:

1 0 1 1 1 0 0 1 0 1 0 0 1 1 1

我似乎无法找到正确的算法来识别此类矩阵中的正方形。谁能给我一个提示?

最佳答案

简单算法:

for(int i = 0; i < rows-2; i++) // scan all but last 2 rows since we scan down once we find the top of a square
    // Reset the count after each row
    int count = 0;
    int lastCell = -1;
    for(int j = 0; j < cols; j++) { // Scan all columns
       // look for 3 cells in a row the same
       if (cells[i][j] == lastCell) {
          count++;
       } else {
          lastCell = cells[i][j];
          count=1;
       }
       if (count >= 3) {
          // Potential match found since we have a row of three the same
          // now check for the sides and bottom
          if (cells[i-2][j+1] == lastCell && cells[i-2][j+2] == lastCell && // left side
              cells[i][j+1] == lastCell && cells[i][j+2] == lastCell && // right side
              cells[i-1][j+2] == lastCell  // bottom
              ) {
                // Square detected - do whatever you like here :)
                // i, j is the top right corner of the detected square
           }
       }
    }

如果您需要正方形是空心的,请检查中心正方形 != lastCell。

如果您只需要某个值的平方,则只检查该值。

关于c - 在矩阵中查找正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578178/

相关文章:

c++ - 为什么 uintptr_t 和 intptr_t 在 C(和 C++)标准中是可选类型?

c++ - 加权 boolean 值 - 缩放

algorithm - 在 O(n) 时间内用排序的 y 坐标制作优先搜索树

javascript - 计算矩阵的行列式

c - 错误: initialization with “{…}” expected for aggregate object - c

c - 如何使用指针复制字符串

c - 试图找到两个数组的非支配解

algorithm - 在二进制位图中选择最大数量的非重叠 2x2 方 block

r - 表示每个组内有超过 1 列的组索引

C++ 求矩阵最小和最大元素之间的元素和