Java. using 2 variables instead of 4 -> top, bottom, left, right


  • 0
    U
    public class Solution {
        public int[][] generateMatrix(int n) {
            if(n==0) return new int[0][];
            int i=0, j=-1, row =n, col =n, val=0, valSquare = n*n;
            int[][] matrix = new int[n][n];
            boolean flag = false;
            while(true){
                for(++j;j<col && matrix[i][j]==0;j++){
                    matrix[i][j]=++val;
                    //System.out.println(val);
                    flag=true;
                } if(flag) {--j;flag=false;}
                if(val==valSquare) break;
                
                for(++i;i<row && matrix[i][j]==0;i++){
                    matrix[i][j]=++val;
                    flag=true;
                } if(flag) {--i;flag=false;}
                if(val==valSquare) break;
                
                for(--j;j>=0 && matrix[i][j]==0;j--){
                    matrix[i][j]=++val;
                    flag=true;
                }if(flag){++j;flag=false;}
                if(val==valSquare) break;
                
                for(--i;i>=0 && matrix[i][j]==0;i--){
                    matrix[i][j]=++val;
                    flag=true;
                }if(flag){++i;flag=false;}
                if(val==valSquare) break;
            }
            return matrix;
        }
    }
    

Log in to reply
 

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