C solution

  • 7
    int** matrixReshape(int** nums, int m, int n, int r, int c, int** columnSizes, int* returnSize) {
        if (r * c != m * n) {
            r = m;
            c = n;
        *returnSize = r;
        int** result = (int**) malloc(r * sizeof(int*));
        *columnSizes = (int*) malloc(r * sizeof(int));
        for (int i = 0; i < r; ++i) {
            result[i] = (int*) malloc(c * sizeof(int));
            (*columnSizes)[i] = c;
        for (int i = 0; i < m * n; ++i)
            result[i/c][i%c] = nums[i/n][i%n];
        return result;

    Most of the code is for creating the data structure, not for writing the real contents into it. This must be fun for masochists :-). I just did this because of @leaf2's question about C solutions and similar questions I've seen occasionally. Was a little challenge.

    Things to notice:

    • If the requested shape is invalid, we can't just return nums (which is what the problem text somewhat sounds like). Think about what the judge is probably doing. Probably it uses and frees all the result data (the data pointed to by the return value as well as what we write in returnSize and columnSizes). So we should create an independent copy of the input matrix with all its own data. I do this by simply changing r and c to the input shape and then continuing as otherwise. Can also be done like this:

       if (r * c != m * n)
           return matrixReshape(nums, m, n, m, n, columnSizes, returnSize);
    • The "sizes" we must write to are the numbers of rows and columns, not the malloc sizes (i.e., not multiplied with sizeof(...)). I found that unclear in the specification, but on the other hand, it makes more sense if you think about what the judge code probably looks like.

    • I renamed numsRowSize and numsColSize to the standard matrix size names m and n. Can't stand those awfully long and nonstandard names.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.