Problem

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).

Example

Given ::
[
[1,2,3],
[4,5,6],
[7.8,9]
]
Output ::
[
[7,4,1],
[8,5,2],
[9.6,3]
]

JavaScript Code

function rotate(matrix) {
    var n = matrix.length;
    for (var i = 0; i < n / 2; i++) {
        for (var j = 0; j < Math.ceil(n/2); j++) {
            var temp = matrix[i][j];
            matrix[i][j] = matrix[n-1-j][i];
            matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
            matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
            matrix[j][n-1-i] = temp;
        }
    }
    return matrix;
}

2 comments:

  1. You should be using Math.floor, not Math.ceil. Test your code out on a 3x3 Matrix.

    ReplyDelete
  2. And there is a period in your arrays

    ReplyDelete

Blogroll

Popular Posts