C 在矩阵中查找平方

C 在矩阵中查找平方,c,algorithm,matrix,multidimensional-array,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是实际的“行”。我知道要遍历矩阵,我需要使用两个嵌套循环,如下所示: 3 5 1 0 1 1 1 0 0 1 0 1 0 0 1 1 1 for(int

我很难想出一个算法来遍历一个由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是实际的“行”。我知道要遍历矩阵,我需要使用两个嵌套循环,如下所示:

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 */
我似乎找不到正确的算法来识别这类矩阵中的正方形。谁能给我一个提示吗?

简单算法:

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
           }
       }
    }
for(int i=0;i=3){
//发现潜在匹配,因为我们有三个相同的行
//现在检查侧面和底部
如果(单元格[i-2][j+1]==lastCell&&cells[i-2][j+2]==lastCell&&//左侧
单元格[i][j+1]==lastCell&&cells[i][j+2]==lastCell&&//右侧
单元格[i-1][j+2]==最后一个单元格//底部
) {
//检测到方形-在此处执行任意操作:)
//i,j是检测到的正方形的右上角
}
}
}
如果您需要正方形为空心,请检查中心正方形!=最后一个细胞


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

这不清楚。在您的示例中,您希望得到什么结果?“我需要能够在矩阵中保存正方形的左上角坐标和右下角坐标”-嗯?看起来您需要四个变量。这是你的问题吗?是的,我知道那部分,“正方形识别”部分就是你没有提到的部分…太好了,这帮了大忙!谢谢