Straightforward Java Solution based on Spiral Matrix


  • 0
    X
    public int[][] generateMatrix(int n) {
        int[][]result=new int[n][n];
        int rowBegin=0,rowEnd=n-1;
        int colBegin=0,colEnd=n-1;
        
        int[]num=new int[n*n];
        num[0]=1;
        for(int i=1;i<n*n;i++){
            num[i]=num[i-1]+1;
        }
        
        int count=0;
        while(rowBegin<=rowEnd&&colBegin<=colEnd){
            //Traverse Right
            for(int j=colBegin;j<=colEnd;j++){
                result[rowBegin][j]=num[count];
                count++;
            }
            rowBegin++;
            //Traverse Down
            for(int i=rowBegin;i<=rowEnd;i++){
                result[i][colEnd]=num[count];
                count++;
            }
            colEnd--;
            //Traverse Left
            for(int j=colEnd;j>=colBegin;j--){
                result[rowEnd][j]=num[count];
                count++;
            }
            rowEnd--;
            //Traverse up
            for(int i=rowEnd;i>=rowBegin;i--){
                result[i][colBegin]=num[count];
                count++;
            }
            colBegin++;
        }
        return result;
    }
    

    Use two pointers to modify the scale of the for loop dynamically.


Log in to reply
 

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