Javascript Solution: Transpose and Swap


  • 0

    Note that I return the matrix in the driving method, so this solution won't work as-is in the compiler here. Remove the return to test it.

    var rotate = function(matrix) {
        matrix = transposeMatrix(matrix);
        return swapColumns(matrix);
    };
    
    // Converts cols to rows, rows to cols of a matrix
    function transposeMatrix(m) {
        if (m) {
            var n = m.length;
            for (var i = 0; i < n; i++) {
                for (var j = i + 1; j < n; j++) {
                    var temp = m[i][j];
                    m[i][j] = m[j][i];
                    m[j][i] = temp;
                }
            }
            return m;
        }
        return null;
    }
    
    function swapColumns(m) {
        var n = m.length
        for(var i = 0; i < n; i++) {
            for(var j = 0; j < n/2; j++) {
                var temp = m[i][j];
                m[i][j] = m[i][n - 1 - j];
                m[i][n - 1 - j] = temp;
            }
        }
        return m;
    }
    

  • 0

    Here's a complete solution for rotation in both directions:

    Algorithm: For rotating right

    • Transpose the matrix
    • Swap values for columns

    Algorithm: For rotating left

    • Transpose the matrix
    • Swap values for rows

    Code:

    var rotateBy90Right = function(m) {
        m = transposeMatrix(m);
        return swapColumns(m);
    };
    
    var rotateBy90Left = function(m) {
        m = transposeMatrix(m);
        return swapRows(m);
    };
    
    // Converts cols to rows, rows to cols of a matrix
    function transposeMatrix(m) {
        if (m) {
            var n = m.length;
            for (var i = 0; i < n; i++) {
                for (var j = i + 1; j < n; j++) {
                    var temp = m[i][j];
                    m[i][j] = m[j][i];
                    m[j][i] = temp;
                }
            }
            return m;
        }
        return null;
    }
    
    // Swap the elements of the columns
    function swapRows(m) {
        var n = m.length
        for(var i = 0; i < n/2; i++) {
            for(var j = 0; j < n; j++) {
                var temp = m[i][j];
                m[i][j] = m[n - 1 - i][j];
                m[n - 1 - i][j] = temp;
            }
        }
        return m;
    }
    
    function swapColumns(m) {
        var n = m.length
        for(var i = 0; i < n; i++) {
            for(var j = 0; j < n/2; j++) {
                var temp = m[i][j];
                m[i][j] = m[i][n - 1 - j];
                m[i][n - 1 - j] = temp;
            }
        }
        return m;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.