JAVA Solution From outer side to inner side


  • 0
    Y
    public class Solution {
        public int[][] generateMatrix(int n) {
            int layer = (n - 1) / 2;
            int l = 0;
            int len = n - 1;
            int[][] res = new int[n][n];
            int count = 1;
            while(l <= layer){
                for(int i=l; i<=len; i++)
                    res[l][i] = count++;
                for(int i=l+1; i<len; i++)
                    res[i][len] = count++;
                for(int i=len; i>l; i--)
                    res[len][i] = count++;
                for(int i=len; i>l; i--)
                    res[i][l] = count++;
                l += 1;
                len -= 1;
            }
            return res;
        }
    }

Log in to reply
 

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