# LeetCode - 0566. Reshape the Matrix ### 題目網址:https://leetcode.com/problems/reshape-the-matrix/ ###### tags: `LeetCode` `Easy` `模擬` `陣列` ```cpp= /* -LeetCode format- Problem: 566. Reshape the Matrix Difficulty: Easy by Inversionpeter */ class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { if (!nums.size() || r <= 0 || c <= 0 || r * c != nums.size() * nums[0].size()) return nums; vector <vector <int>> newMatrix; int nowRow = 0, nowColumn = 0; newMatrix.resize(r), newMatrix[0].resize(c); for (int i = 0; i != nums.size(); ++i) for (int j = 0; j != nums[i].size(); ++j) { if (nowColumn == c) { ++nowRow, nowColumn = 0; if (nowRow != r) newMatrix[nowRow].resize(c); } newMatrix[nowRow][nowColumn] = nums[i][j], ++nowColumn; } return newMatrix; } }; ```