Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Reshape the Matrix ใน C++

แนวคิด

ในแพลตฟอร์มต่างๆ มีฟังก์ชัน 'reshape' ที่ใช้เปลี่ยนรูปเมทริกซ์เป็นใหม่ขนาดต่างกันแต่ข้อมูลเหมือนเดิม ถ้ามีเมทริกซ์และค่า r, c สำหรับแถวและคอลัมน์ของเมทริกซ์ที่ต้องการ

เช่น ถ้าอินพุตคือ [[5,10],[15,20]], row = 1 และ col = 4 ผลลัพธ์คือ [[5, 10, 15, 20]]

วิธีแก้:

  • กำหนดอาร์เรย์ temp
  • กำหนดอาร์เรย์ 2D res ขนาด (r x c)
  • count := 0
  • วนลูป i := 0 ถึงขนาด nums - 1:
    • วนลูป j := 0 ถึงขนาด nums[0] - 1: แทรก nums[i,j] ลงท้าย temp
  • ถ้า r * c ไม่เท่ากับขนาด nums: คืนค่า nums
  • วนลูป i := 0 ถึง r - 1:
    • วนลูป j := 0 ถึง c - 1: count = count + 1, res[i,j] := temp[count]
  • คืนค่า res

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto>> v) {
    cout << "[";
    for(int i = 0; i<v.size(); i++) {
        cout << "[";
        for(int j = 0; j<v[i].size(); j++) {
            cout << v[i][j] << ", ";
        }
        cout << "],";
    }
    cout << "]"<<endl;
}
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        vector<int> temp;
        vector<vector<int>> res(r, vector<int>(c));
        int count = 0;
        for (int i = 0; i < nums.size(); i++) {
            for (int j = 0; j < nums[0].size(); j++) {
                temp.push_back(nums[i][j]);
            }
        }
        if (r * c != nums.size() * nums[0].size())
            return nums;
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                res[i][j] = temp[count++];
            }
        }
        return res;
    }
};
main() {
    Solution ob;
    vector<vector<int>> v = {{5,10},{15,20}};
    print_vector(ob.matrixReshape(v, 1, 4));
}

อินพุต

{{5,10},{15,20}}, 1, 4

เอาต์พุต

[[5, 10, 15, 20, ],]