Matrix Rotation (In Memory)
Thinking Process:
- We have to iterate over the columns of the matrix and keep adding elements in a queue starting from the last row of each column.
- Now, simply empty the queue into the matrix.
NOTE: By adding the elements into the queue in the above fashion, we are creating a queue which will effectively produce a rotated image (if updated in the matrix in a row-wise manner).
Now if we look at the image closely, we will observe that each column (from bottom to up) becomes a row after rotation.
This is the sequence we are creating in the queue.
public void rotate(int[][] matrix) {
Queue<Integer> q = new LinkedList<>();
for(int j=0;j<matrix[0].length;j++){ //iterate over columns
for(int i=matrix.length-1;i>=0;i--){ //last row to 0th row
q.add(matrix[i][j]);
}
}
while(!q.isEmpty()){
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++)
matrix[i][j] = q.poll();
}
}
}
Comments
Post a Comment