Reshape the Matrix

🏠 ⬅️ ➡️

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]]

Example 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4 Output: [[1,2],[3,4]]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    integer, parameter :: m = 2, n = 2
    integer, parameter :: r = 1, c = 4
    integer :: i, j
    integer :: mat(m, n) = reshape([1, 2, 3, 4], shape(mat))
    integer :: reshaped_mat(r, c)

    write(*,*) "Original matrix:"
    do i = 1, m
        write(*,"(5(I3,1X))") mat(i,:)
    end do

    if (size(mat, 1) * size(mat, 2) == r * c) then
        reshaped_mat = reshape(mat, shape(reshaped_mat))
        write(*,*) "Reshaped matrix:"
        do i = 1, r
            write(*,"(5(I3,1X))") reshaped_mat(i,:)
        end do
    else
        write(*,*) "Original matrix:"
        do i = 1, m
            write(*,"(5(I3,1X))") mat(i,:)
        end do
    end if

end program main
Compiled
Executed
Correct
program reshape
      implicit none

      integer, parameter :: m = 2, n = 2
      integer, parameter :: r = 1, c = 4

      integer :: i, j
      integer :: mat(m, n)
      integer :: reshaped_mat(r, c)

      ! Initialize the matrix
      mat = reshape((/ 1, 2, 3, 4 /), shape=(/ m, n /))

      ! Reshape the matrix
      reshaped_mat = reshape(mat, shape=(/ r, c /))

      ! Print the reshaped matrix
      do i = 1, r
          write (*,*) reshaped_mat(i, :)
      end do

      end program

This program defines two parameters `m` and `n` to represent the number of rows and columns of the original matrix, and two parameters `r` and `c` to represent the number of rows and columns of the wanted reshaped matrix. It then declares an `m x n` matrix `mat` and an `r x c` matrix `reshaped_mat`.

The program initializes the `mat` matrix with the values `1, 2, 3, 4` using the `reshape` function, which takes an array of values and reshapes it into a matrix with the given shape.

The program then reshapes the `mat` matrix into the `reshaped_mat` matrix using the `reshape` function again, this time with the shape of the wanted reshaped matrix.

Finally, the program prints the `reshaped_mat` matrix to the console using a `do` loop.

Note that this program assumes that the `reshape` function is available in the Fortran standard library. If your compiler does not support this function, you may need to use a different method to reshape the matrix.
🌐 Data from online sources
def matrixReshape(mat, r, c):
    m, n = len(mat), len(mat[0])
    if m * n != r * c:
        return mat

    reshaped = [[0] * c for _ in range(r)]
    for i in range(m * n):
        reshaped[i // c][i % c] = mat[i // n][i % n]

    return reshaped

The algorithm works by first checking if the reshape operation is possible. If the total number of elements in the original matrix (m * n) is not equal to the number of elements the reshaped matrix should have (r * c), the original matrix is returned.

If the reshape operation is possible, we create a new matrix of size r x c. We then iterate through each element index (i) of the original matrix and calculate the corresponding row and column in the reshaped matrix (i / c and i % c), assigning the value from the original matrix (mat[i / n][i % n]) to its position in the reshaped matrix.

Finally, we return the reshaped matrix.

🌐 Data from online sources
#include <vector>
using namespace std;

vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
    int m = mat.size();
    int n = mat[0].size();
    if (m * n != r * c) {
        return mat;
    }

    vector<vector<int>> reshaped(r, vector<int>(c));
    for (int i = 0; i < m * n; ++i) {
        reshaped[i / c][i % c] = mat[i / n][i % n];
    }

    return reshaped;
}

The algorithm works by first checking if the reshape operation is possible. If the total number of elements in the original matrix (m * n) is not equal to the number of elements the reshaped matrix should have (r * c), the original matrix is returned.

If the reshape operation is possible, we create a new matrix of size r x c. We then iterate through each element index (i) of the original matrix and calculate the corresponding row and column in the reshaped matrix (i / c and i % c), assigning the value from the original matrix (mat[i / n][i % n]) to its position in the reshaped matrix.

Finally, we return the reshaped matrix.