[LeetCode] July LeetCoding Challenge 2021 - Week 1 Reshape the Matrix (6th, July)


Reshape the Matrix


📃 Problem


https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/608/week-1-july-1st-july-7th/3803/

💡 Check Point

  • Determine whether given values r, c are possible and legal.
  • Determine how to create a reshaped matrix from an original matrix.
  • 👩‍💻 My Solution

    
    class Solution {
    public:
    
        vector<vector<int> > matrixReshape(vector<vector<int> >& mat, int r, int c) {
            vector<vector<int> > result;
    		
            // Define original matrix's row and column
            // m = original row, n = original colum
            int m = mat.size();
            int n = mat[0].size();
    		
            // If we could not create a reshaped matrix with using given values c, r
            // => return an origianl matrix
            if(r*c != m*n) {
                return mat;
            }
    
    		
            // Otherwise, create a reshaped matrix!
            for(int i = 0; i < r; i++) {
                vector<int> values;
    
                for(int j = 0; j < c; j++) {
                	// Define k which calculate a new matrix's 1d index
                    int k = c * i + j;
                    
                    // Calculate 2d indices using 1d index
                    values.push_back(mat[k/n][k%n]);
                }
    
                result.push_back(values);
            }
    
            return result;
        }
    };