Topic describes

In MATLAB, there is a very useful function 0 that remolds one matrix into another new matrix of a different size, but preserves its original data.

Give a matrix represented by a two-dimensional array, and two positive integers r and C, representing the number of rows and columns of the desired reconstructed matrix, respectively.

The reconstructed matrix requires that all elements of the original matrix be filled in the same row traversal order.

0 0 If the 0 0 operation with the given parameters is 0 0 0 0 0 Otherwise, output the original matrix.

Example 1:

Input: nums = [[1, 2], [3, 4]] r = 1, c = 4 output: [[1, 2, 3, 4]] : traveled through the nums as a result of [1, 2, 3, 4]. The new matrix is a 1 by 4 matrix, and the new matrix is filled row by row with the values of the previous elements. Example 2:

Input: nums = [[1, 2], [3, 4]] r = 2, c = 4 output: [[1, 2], [3, 4]] : there is no way to translate into 2 * 2 * 2 matrix 4 matrix. So output the original matrix.

Copyright belongs to LeetCode. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Thought analysis

First determine whether the conversion, and then create a two-dimensional array, through the calculation of location reassignment

AC code

int支那matrixReshape(int** nums, int numsSize, int* numsColSize, int r, int c, int* returnSize, int** returnColumnSizes){
    if(numsSize * (*numsColSize) ! = r * c) { *returnSize = numsSize; *returnColumnSizes =calloc(numsSize, sizeof(int));
        for (int i = 0; i < numsSize; i++) {
            (*returnColumnSizes)[i] = numsColSize[i];
        }
        return nums;
    }

    int **res = calloc(r, sizeof(int *));

    *returnSize = r;
    *returnColumnSizes = calloc(r, sizeof(int));

    const int count = r * c;
    for (int i = 0; i < r; ++i) {
        (*returnColumnSizes)[i] = c;
        res[i] = calloc(c, sizeof(int));
    }
    for (int i = 0; i < count; i++) {
        res[i / c][i % c] = nums[i / (*numsColSize)][i % (*numsColSize)];
    }

    return res;
}
Copy the code

conclusion

Simple two-dimensional array location problem

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign