Extremely Clear Java Solution

  • 0

    Maintain indices for left, right, top, and bottom.

    Fill each row then reel them in. If odd, then fill in the center at the end.

    Maintain a counter that is incremented every time.

    The key to not fucking this up is two-fold:

    1. Make sure you don't overlap on the corners (very easy to do)
    2. Make sure you don't fuck up the direction of the inserts (also a very easy mistake)

    Just take your time and think it through.

    class Solution {
        int count;
        public int[][] generateMatrix(int n) {
            int[][] tr = new int[n][n];
            count = 1;
            int top = 0;
            int bottom = n-1;
            int left = 0;
            int right = n-1;
            while(top < bottom){
                fillTop(tr, top, left, right);
                fillRight(tr, right, top, bottom);
                fillBottom(tr, bottom, right, left);
                fillLeft(tr, left, bottom, top);
                tr[n/2][n/2] = count;
            // Fill in middle
            return tr;
        void fillTop(int[][] tr, int top, int left, int right){
            for(int i=left;i<=right;i++){
                tr[top][i] = count++;
        void fillRight(int[][] tr, int right, int top, int bottom){
            for(int i=top+1;i<=bottom;i++){
                tr[i][right] = count++;
        void fillBottom(int[][] tr, int bottom, int right, int left){
            for(int i=right-1;i>=left;i--){
                tr[bottom][i] = count++;
        void fillLeft(int[][] tr, int left, int bottom, int top){
            for(int i=bottom-1;i>top;i--){
                tr[i][left] = count++;

Log in to reply

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