Share my concise java solution


  • 0
    N
    public int[][] generateMatrix(int n) {
        //if(n <= 0) return new int[0][0];
        int rowLen = n;
        int colLen = n;
        
        int row = 0;
        int col = -1;
        int num = 1;
        int[][] matrix = new int[n][n];
        
        while(true){
            for(int i = 0; i < colLen; i++){
                matrix[row][++col] = num++;
            }
            
            if(--rowLen <= 0) break;
            
            for(int i = 0; i < rowLen; i++){
                matrix[++row][col] = num++;
            }
            
            if(--colLen <= 0) break;
            
            for(int i = 0; i < colLen; i++){
                matrix[row][--col] = num++;
            }
            
            if(--rowLen <= 0) break;
            
            for(int i = 0; i < rowLen; i++){
                matrix[--row][col] = num++;
            }
            if(--colLen <= 0) break;
        }
        
        return matrix;
    }

Log in to reply
 

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