Spiral Matrix

Problem

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example, Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Solution

Concise Solution with For Loops Inside

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int num = 1;
        int rowBegin = 0, rowEnd = n  - 1, colBegin = 0, colEnd = n - 1;
        while (num <= n * n) {
            //Right 
            for(int i = colBegin; i <= colEnd; i++) matrix[rowBegin][i] = num++;
            rowBegin++; //Reach the border, turn down
            //Down
            for (int i = rowBegin; i <= rowEnd; i++) matrix[i][colEnd] = num++;
            colEnd--; //Turn left
            //Left
            for (int i = colEnd; i >= colBegin; i--) matrix[rowEnd][i] = num++;
            rowEnd--; //Turn Up
            //Up
            for (int i = rowEnd; i >= rowBegin; i--) matrix[i][colBegin] = num++;
            colBegin++;
        }
        return matrix;
    }
}

Analysis

Instead of using a lot of if statements and direction var
We use for loops inside to imitate the spiral order straight
We have some vars to indicate the border of current matrix
And we always use the updated vars not n to fill the matrix

results matching ""

    No results matching ""