Problem: Rotate Image

ANKUSH KUMARANKUSH KUMAR
1 min read

1.png

2.png

class Solution {
    public void rotate(int[][] matrix) {
        for (int col = 0; col < matrix[0].length; col++){
            for (int row = 0; row < matrix.length/2; row++){
                swap(matrix, row, col, matrix.length-row-1, col);
            }
        }

        for (int i = 0; i < matrix.length; i++){
            for (int j = i; j < matrix[0].length; j++){
                swap(matrix, i,j, j, i);
            }
        }
    }

    private void swap(int[][] matrix, int x1, int y1, int x2, int y2){
        int temp = matrix[x1][y1];
        matrix[x1][y1] = matrix[x2][y2];
        matrix[x2][y2] = temp;
    }
}
1
Subscribe to my newsletter

Read articles from ANKUSH KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ANKUSH KUMAR
ANKUSH KUMAR

({MERN Stack Developer at mackph}) | <Ex-Internshala Student Partner(ISP 16)> | <5 star coder at Hackerrank> | <Self employed at Mackph> | <GSSoC '22 Contributor> | <Ex-Campus Ambassador at International MUN>