instagram

Rotate matrix by 90 degrees

Rotate matrix by 90 degrees is very simple please find below algo

//i=0 to n/2
//j=0 to n/2

int temp = matrix[i][j];
matrix[i][j] = matrix[size - j][i];
matrix[size - j][i] = matrix[size - i][size - j];
matrix[size - i][size - j] = matrix[j][size - i];
matrix[j][size - i] = temp;

matrixrotation

Algorithm

public static void rotateMatrix90(int[][] matrix) {

		int n = matrix.length;
		int size = n - 1;

		for (int i = 0; i < n / 2; i++) {

			for (int j = 0; j < Math.ceil(n / 2.0); j++) {

				int temp = matrix[i][j];
				matrix[i][j] = matrix[size - j][i];
				matrix[size - j][i] = matrix[size - i][size - j];
				matrix[size - i][size - j] = matrix[j][size - i];
				matrix[j][size - i] = temp;

			}

		}

	}
Share