首页 > 解决方案 > Create a matrix with elements taken by another matrix

问题描述

I have to implement a function which, given a matrix of 0s and 1s, returns a new matrix that contains the coordinates of the 1s. For example: if matrix is 3x3 and the output is:

1 0 1
0 1 1
0 0 1

New matrix will be 5x2 and the output will be:

0 0
0 2
1 1
1 2
2 2

Some advice? My method would be this:

int matrix[3][3];
for (int i = 0; i < 3; i++){
    for (int j = 0; j < 3; j++){
        if (matrix[i][i] == 1){
            //Code i need
        }
    }
}

标签: cmatrixindexingcopyelement

解决方案


If matrix[i][j] == 1 what do you know about the coordinates [i,j] ? That they are the coordinates of a 1 :)

Secondly, will the input matrix always be 3x3? If not, you'll want to store the dimensions of the matrix in variables, and use theses variables for your for loops.


推荐阅读