Algorithm


Problem Name: 566. 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

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

start coding..
class Solution {
public:
    vector<vector<int>> matrixReshape(vector < vector<int>>& nums, int r, int c) {
        int m = nums.size(), n = nums[0].size();
        if(m * n != r * c) return nums;
        vector<vector < int>>res(r, vector<int>(c));
        int row = 0, col = 0;
        for(int i = 0; i  <  r; i++)
            for(int j = 0; j  <  c; j++){
                res[i][j] = nums[row][col++];
                if(col == n> col = 0, row++;
            }
        return res;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
mat = [[1,2],[3,4]], r = 1, c = 4

Output

x
+
cmd
[[1,2,3,4]]

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int numOfElem = nums.length*nums[0].length;
        if (numOfElem != r*c) {
            return nums;
        }
        
        int[] expandedArray = new int[numOfElem];
        int k = 0;
        
        for (int i=0;i < nums.length;i++) {
            for (int j=0;j < nums[i].length;j++) {
                expandedArray[k] = nums[i][j];
                k++;
            }
        }
        
        int[][] ans = new int[r][c];
        int i=0;
        int j=0;
        for(k=0;k < numOfElem;k++) {
            ans[i][j] = expandedArray[k];
            j++;
            if (j == c) {
                j = 0;
                i++;
            }
        }
        return ans;
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
mat = [[1,2],[3,4]], r = 1, c = 4

Output

x
+
cmd
[[1,2,3,4]]

#3 Code Example with Javascript Programming

Code - Javascript Programming


const matrixReshape = function(nums, r, c) {
  if (isValid(nums, r, c) === false) {
    return nums;
  }
  const arr = [];
  nums.forEach(el => arr.push(...el));
  const res = [];
  for (let start = 0; start  <  arr.length; start = start + c) {
    res.push(arr.slice(start, start + c));
  }
  return res;
};

function isValid(matrix, r, c) {
  if (matrix.length * matrix[0].length !== r * c) {
    return false;
  } else {
    return true;
  }
}

console.log(matrixReshape([[1, 2], [3, 4]], 1, 4));
console.log(matrixReshape([[1, 2], [3, 4]], 2, 4));
Copy The Code & Try With Live Editor

Input

x
+
cmd
mat = [[1,2],[3,4]], r = 2, c = 4

Output

x
+
cmd
[[1,2],[3,4]]

#4 Code Example with Python Programming

Code - Python Programming

start coding...
class Solution:
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        nums_ordered=[x for y in nums for x in y]
        if r*c==len(nums)*len(nums[0]):
            return [nums_ordered[c*i:c*(i+1)] for i in range(r)]
        else:return nums
        
Copy The Code & Try With Live Editor

Input

x
+
cmd
mat = [[1,2],[3,4]], r = 2, c = 4

Output

x
+
cmd
[[1,2],[3,4]]

#5 Code Example with C# Programming

Code - C# Programming


using System.Linq;

namespace LeetCode
{
    public class _0567_PermutationInString
    {
        public bool CheckInclusion(string s1, string s2)
        {
            var s1Length = s1.Length;
            var s2Length = s2.Length;

            if (s1Length > s2Length) return false;

            var s1Count = new int[26];
            foreach (var ch in s1)
                s1Count[ch - 'a']++;

            var s2Count = new int[26];
            for (int i = 0; i  <  s2Length; i++)
            {
                s2Count[s2[i] - 'a']++;
                if (i >= s1Length)
                    s2Count[s2[i - s1Length] - 'a']--;

                if (s2Count.SequenceEqual(s1Count))
                    return true;
            }

            return false;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
mat = [[1,2],[3,4]], r = 1, c = 4

Output

x
+
cmd
[[1,2,3,4]]
Advertisements

Demonstration


Previous
#565 Leetcode Array Nesting Tilt Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#567 Leetcode Permutation in String Solution in C, C++, Java, JavaScript, Python, C# Leetcode