以列方式从二进制矩阵中获取 1 的索引

Obtain Indices of 1s from a Binary Matrix in a Column fashion

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

我实现了一个程序,它以列方式查找 1 的个数的索引。以上面的二元矩阵为例,需要得到的指标有: 0 2 0 1 1 3 0 3 1 2 2 3。

我的问题是,要获得这些索引,我必须额外添加两行全是零的行。我实施的完整工作程序如下:

#include <stdio.h>
#include <stdlib.h>
#define padding 2
#define rows_Matrix 4  + padding
#define cols_Matrix 6

int main() 
{

   int index = 0;

   //Allocation of Memory for the Binary Matrix. 
   unsigned **Matrix = (unsigned**)malloc(sizeof(unsigned*)*rows_Matrix); //Rows

   for (int i = 0; i < rows_Matrix; i++) //Rows
   {
       Matrix[i] = (unsigned *)malloc(sizeof(unsigned) * cols_Matrix); //Columns 
   }

   //Assigning elements to the Binary Matrix. 
   Matrix[0][0] = 1; Matrix[0][1] = 1; Matrix[0][2] = 0; Matrix[0][3] = 1;  Matrix[0][4] = 0;  Matrix[0][5] = 0;
   Matrix[1][0] = 0; Matrix[1][1] = 1; Matrix[1][2] = 1; Matrix[1][3] = 0;  Matrix[1][4] = 1;  Matrix[1][5] = 0;
   Matrix[2][0] = 1; Matrix[2][1] = 0; Matrix[2][2] = 0; Matrix[2][3] = 0;  Matrix[2][4] = 1;  Matrix[2][5] = 1;
   Matrix[3][0] = 0; Matrix[3][1] = 0; Matrix[3][2] = 1; Matrix[3][3] = 1; Matrix[3][4] = 0;  Matrix[3][5] = 1;

   //Added padded rows of 0s to get the Matrix a square in order to obtain indices.
   Matrix[4][0] = 0; Matrix[4][1] = 0; Matrix[4][2] = 0; Matrix[4][3] = 0;  Matrix[4][4] = 0;  Matrix[4][5] = 0;
   Matrix[5][0] = 0; Matrix[5][1] = 0; Matrix[5][2] = 0; Matrix[5][3] = 0;  Matrix[5][4] = 0;  Matrix[5][5] = 0;

   //Finding indices of number of 1s in the columns of the matrix.
   printf("Vertical Indices of 1s in the Matrix:\n");

   for (int i = 0; i < rows_Matrix; i++)
   {
      for (int j = 0; j < cols_Matrix; j++)
      {
         if (Matrix[j][i] == 1)
         {
            index = j;
            //Printing indices of 1s in a column fashion.
            printf("%d\t", index); 
         }
      }
   }
   printf("\n");

  return 0;
}

我实现的程序输出结果如下:

矩阵中 1 的垂直索引: 0 2 0 1 1 3 0 3 1 2 2 3

我想将矩阵保留为 4x6 矩阵而不是 6x6 矩阵,并且仍然获得我在程序中获得的上述索引。有没有办法在不需要在 C 中添加额外填充的情况下获得这些索引?

我认为你的问题出在这里:

for (int i = 0; i < rows_Matrix; i++)
{
   for (int j = 0; j < cols_Matrix; j++)

您需要像这样交换行和列:

for (int i = 0; i < cols_Matrix; i++)  // cols instead of rows
{
   for (int j = 0; j < rows_Matrix; j++)  // rows instead of cols

之后你可以删除填充

预处理器定义

#define rows_Matrix 4  + padding

应该是

#define rows_Matrix (4  + padding)

如果你看这一行

unsigned **Matrix = (unsigned**)malloc(sizeof(unsigned*)*rows_Matrix);

它扩展到

unsigned **Matrix = (unsigned**)malloc(sizeof(unsigned*)*4  + padding);

这与

中的行为不同
for (int i = 0; i < rows_Matrix; i++)

错误是良性的。 始终在预处理器语句周围加上括号。