Categories
Array Loop Matrix

Spiral Matrix

function spiralMatrix(dimension) {

    let matrix = [];
    // create blank matrix based from given dimension
    for (let i = 0; i < dimension; i++) {
        matrix.push(new Array(dimension).fill(0))
    }

    let counter = 1;
    let startRow = 0, endRow = dimension, startColumn = 0, endColumn = dimension;


    while (startRow < endRow && startColumn < endColumn) {

        // top left -> top right
        for (let i = startColumn; i < endColumn; i++) {
            matrix[startRow][i] = counter++;
        }
        startRow++

        // top right -> bottom right
        for (let i = startRow; i < endRow; i++) {
            matrix[i][endColumn - 1] = counter++;
        }
        endColumn--;

        // bottom right -> bottom left
        for (let i = endColumn - 1; i >= startColumn; i--) {
            matrix[endRow - 1][i] = counter++;
        }
        endRow--;


        // bottom left -> top left
        for (let i = endRow; i > startRow; i--) {
            matrix[i - 1][startColumn] = counter++;
        }
        startColumn++;

    }

     return matrix;
}