I'm trying to go over the problems in the Cracking the Coding Interview book. One of the questions asks me to rotate a matrix 90 degrees clockwise. Now, while trying to solidify my understanding of matrix rotation, I tried to embark on a new problem: to try to rotate a matrix 90 degrees counterclockwise (the other direction).
I've tried to go through layers of a square matrix, the outer layer, iterating all the way into the inner layer and rotating all the indexes of each side of the "square" one by one. This basically is what Gayle Laakman McDowell's solution implemented, but the other direction.
public static void rotateMatrix(int[][] matrix) {
if (matrix.length == 0) {
return;
}
for (int i = 0; i < matrix.length / 2; i++) {
int top = i;
int bottom = matrix.length - 1 - i;
for (int j = top; j < bottom; j++) {
int temp = matrix[top][j];
matrix[top][j] = matrix[j][matrix.length - 1 - j];
matrix[j][matrix.length - 1 - j] = matrix[bottom][j];
matrix[bottom][j] = matrix[j][matrix.length - 1 - bottom];
matrix[j][matrix.length - 1 - bottom] = temp;
}
}
}
I expected the result of a sample matrix
[1,2,3]
[4,5,6]
[7,8,9]
to be
[3,6,9]
[2,5,8]
[1,4,7]
but my code resulted in
[1,5,7]
[2,8,6]
[3,4,9]
Where is the flaw/discrepancy in my code?