Naive solution without recursion


  • 0
    Z

    Very easy to understand. No need to think about tricky directions.

    t, b, l, r are the offsets from top/bottom/left/right.
    lvl stores how many levels the cursor has advanced.

    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] M = new int[n][];
            for (int i=0; i<n; i++) {
                M[i] = new int[n];
                for (int j=0; j<n; j++) {
                    M[i][j] = get(i, j, n) + 1;
                }
            }
            return M;
        }
        
        public int get(int i, int j, int n) {
            int t = i-0;
            int b = n-1-i;
            int l = j-0;
            int r = n-1-j;
            int lvl = min(t,b,l,r);
            int base = 4*lvl*(n - lvl); // n^2 - (n-2*lvl)^2
            t -= lvl;
            b -= lvl;
            l -= lvl;
            r -= lvl;
            n -= 2*lvl;
            if (t == 0) return base + l;
            if (r == 0) return base + n-1 + t;
            if (b == 0) return base + 2*n - 2 + r;
            return base + 3*n - 3 + b;
        }
        
        public int min(int a, int b, int c, int d) {
            return Math.min(Math.min(a, b), Math.min(c, d));
        }
    }

Log in to reply
 

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