Straightforward solution with brief explanation

  • 0

    The algorithm is to exactly follow the spiral order to fill in the values. The important detail is to change the lower and upper bounds for both row and column directions during iteration.

    Code in Java:

    public int[][] generateMatrix(int n) {
        int rowStart = 0;
        int rowEnd = n-1;
        int colStart = 0;
        int colEnd = n-1;
        int count = 0;
        int[][] res = new int[n][n];
        while(count < n*n) {
            for(int j=colStart; j<=colEnd; j++) {
                res[rowStart][j] = ++count;
            for(int i=rowStart; i<=rowEnd; i++) {
                res[i][colEnd] = ++count;
            for(int j=colEnd; j>=colStart; j--) {
                res[rowEnd][j] = ++count;
            for(int i=rowEnd; i>=rowStart; i--) {
                res[i][colStart] = ++count;
        return res;

Log in to reply

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