Skip to content

Instantly share code, notes, and snippets.

@aniruddha84
Created January 17, 2018 18:13
Show Gist options
  • Save aniruddha84/4e16a33c69e7ac6b3add1c4d7bbf7419 to your computer and use it in GitHub Desktop.
Save aniruddha84/4e16a33c69e7ac6b3add1c4d7bbf7419 to your computer and use it in GitHub Desktop.
Reshape Matrix
class Solution {
public int[][] reshapeMatrix(int[][] matrix, int r, int c) {
int rows = matrix.length;
int cols = matrix[0].length;
if ((rows * cols) != (r * c)) throw new RuntimeException("Invalid operation");
int[][] resultMatrix = new int[r][c];
int resultRow = 0;
int resultCol = 0;
// traverse original matrix and fill in the result matrix
for(int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
resultMatrix[resultRow][resultCol] = matrix[i][j];
if (resultCol == c - 1) {
resultCol = 0;
resultRow += 1;
} else {
resultCol += 1;
}
}
}
return resultMatrix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment