Created
January 17, 2018 18:13
-
-
Save aniruddha84/4e16a33c69e7ac6b3add1c4d7bbf7419 to your computer and use it in GitHub Desktop.
Reshape Matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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