Java solution, easy understand, clear structure


  • 0
    R
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int startX=0, startY=0, endX=n-1, endY=n-1, num=1;;
        while(true){
            for(int index=startX; index<=endX;index++){
                result[startY][index]=num++;
            }
            startY++;
            if(startY>endY) break;
            
            for(int index=startY; index<=endY;index++){
                result[index][endX]=num++;
            }
            endX--;
            if(endX<startX) break;
            
            for(int index=endX; index>=startX;index--){
                result[endY][index]=num++;
            }
            endY--;
            if(endY<startY) break;
            
            for(int index=endY; index>=startY;index--){
                result[index][startX]=num++;
            }
            startX++;
            if(startX>endX) break;
            
        }
        return result;
    }

Log in to reply
 

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