Java solution with simple code.


  • 0
    A
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] res = new int[n][n];
            if (n == 0){
                return res;
            }
            int row = n;
            int col = n;
            int i = 0;
            int j = 0;
            int rowStart = 0;
            int colStart = 0;
            int num = 1;
            while (colStart < col && rowStart < row){
                while (j < col){
                    res[i][j++] = num++;
                }
                rowStart++;
                j--;
                i++;
                while (i < row){
                    res[i++][j] = num++;
                }
                col--;
                i--;
                j--;
                while (j >= colStart){
                    res[i][j--] = num++;
                }
                row--;
                j++;
                i--;
                while (i >= rowStart){
                    res[i--][j] = num++;
                }
                colStart++;
                i++;
                j++;
            }
            return res;
        }
    }

Log in to reply
 

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