Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Reshape the Matrix trong C++


Cho ma trận 2D và hai số r, c. Hãy biến đổi ma trận thành kích thước r x c (giữ nguyên thứ tự phần tử theo hàng). Nếu không thể (số phần tử không khớp), trả về ma trận gốc.

Ví dụ: [[5,10],[15,20]], r=1, c=4 → [[5,10,15,20]]

Giải thuật

  1. Kiểm tra nếu r * c != m * n thì trả về ma trận gốc.
  2. Làm phẳng ma trận gốc thành mảng 1D.
  3. Điền vào ma trận mới kích thước r x c theo thứ tự.

Ví dụ triển khai C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        int m = mat.size(), n = mat[0].size();
        if (r * c != m * n) return mat;
        
        vector<int> flat;
        for (auto& row : mat)
            for (int x : row) flat.push_back(x);
        
        vector<vector<int>> res(r, vector<int>(c));
        for (int i = 0; i < r; i++)
            for (int j = 0; j < c; j++)
                res[i][j] = flat[i * c + j];
        return res;
    }
};

// Helper in ma trận
void print_matrix(vector<vector<int>> v) {
    cout << "[";
    for (int i = 0; i < v.size(); i++) {
        cout << "[";
        for (int j = 0; j < v[i].size(); j++)
            cout << v[i][j] << (j+1<v[i].size()?", ":"");
        cout << "]" << (i+1<v.size()?", ":"");
    }
    cout << "]" << endl;
}

int main() {
    Solution ob;
    vector<vector<int>> v = {{5,10},{15,20}};
    print_matrix(ob.matrixReshape(v, 1, 4)); // [[5,10,15,20]]
    return 0;
}

Đầu vào / Đầu ra

Input: {{5,10},{15,20}}, 1, 4
Output: [[5,10,15,20]]