Leetcode 566. Reshape the Matrix
Approach
First check to make sure there's enough elements in the original matrix to meet the new row and column requirements. I did this by creating a new list to store all of the original values (which we will then use later to fill the new matrix) and then get the count of the list and ensure it's the same as the required amount of rows and columns by multiplying r * c and comparing to the count.
If there's not enough, just return the original matrix.
If there is enough, create the new matrix and keep track of what posisiton we're at in the list of original values. Then iterate through the rows and columns and at each new row initialize the column array. At each column add the value and increment the original position.
Code
public class Solution {
public int[][] MatrixReshape(int[][] mat, int r, int c)
{
//create new list to store original values
var nums = new List<int>();
//iterate through original matrix adding values to list
for(int row = 0; row < mat.Length; row++)
{
for(int col = 0; col < mat[row].Length; col++)
{
nums.Add(mat[row][col]);
}
}
//check that there's enough values to fill up required rows and columns
if((r * c) != nums.Count)
{
//if there's not enough, return original matrix
return mat;
}
//create new matrix
var answer = new int[r][];
//keep track of position in the list of original values
var originalPos = 0;
//iterate through rows and columns adding the value at the current
//position in the list of original numbers
for(int row = 0; row < r; row++)
{
//in C# you have to manually create the new columns
//so do this when we loop to a new row
answer[row] = new int[c];
for(int col = 0; col < c; col++)
{
answer[row][col] = nums[originalPos];
//iterate position in list of original numbers
originalPos++;
}
}
return answer;
}
}