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;
}
我实施的计划的输出如下:
矩阵中1s的垂直指数: 0 2 0 1 1 3 0 3 1 2 2 3
我想将矩阵保留为4x6矩阵而不是6x6矩阵,并且仍然可以获得我在程序中获得的上述索引。有没有办法获得这些索引而无需在C中添加额外的填充?
答案 0 :(得分:0)
我认为你的问题在这里:
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
执行此操作后,您可以删除填充
答案 1 :(得分:0)
预处理器定义
#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++)
错误是良性的。 始终将括号放在预处理程序语句周围。