Straightforward Java solution

  • 0
    public int[][] generateMatrix(int n) {
        int result[][] = new int[n][n];
        for(int up=0,down=n-1,left=0,right=n-1,num=1;up<=down;up++,left++,down--,right--){
            for(int i=up,j=left;i<=down&&j<=right;num++){
                if(result[i][j]!=0) break;
                if(i==up&&j<right) j++;
                else if(i<down&&j==right) i++;
                else if(i==down&&j>left) j--;
                else if(i>up&&j==left) i--;
        return result;

Log in to reply

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