Simple and clean Java Solution


  • 0
    V
    public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] spiralMatrix=new int[n][n];
        if(n == 0) return spiralMatrix;
            
            int left=0,right=spiralMatrix[0].length-1,top=0,bottom=spiralMatrix.length-1,direction=0,k=1;
            while(left <= right && top <= bottom){
                if(direction == 0){
                    for(int i=left;i<= right;i++){
                        spiralMatrix[top][i]=k;
                        k++;
                    }
                    top++;
                }
                else if(direction == 1){
                    for(int i=top;i<=bottom;i++){
                        spiralMatrix[i][right]=k;
                        k++;
                    }
                    right--;
                }
                else if(direction == 2){
                    for(int i=right;i>=left;i--){
                        spiralMatrix[bottom][i]=k;
                        k++;
                    }
                    bottom--;
                    
                }
                else if(direction == 3){
                    for(int i=bottom;i>=top;i--){
                        spiralMatrix[i][left]=k;
                        k++;
                    }
                    left++;
                }
                direction=(direction+1) % 4;
            }
        return spiralMatrix;
    }
    

    }


Log in to reply
 

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