java solution


  • 0
    P
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] matrix = new int[n][n];
            if(n == 0)
            {
                return matrix;
            }
            int left = matrix[0].length-1;
            int right = 0;
            int bottom = matrix.length-1;
            int top = 0;
            int count = 1;
            while(true)
            {
                for(int j = right;j<=left;j++)
                {
                    matrix[top][j] = count;
                    count++;
                }
                top++;
                //Can be deleted
    /*          if(bottom<top||left<right)
                {
                    break;
                }
    */
                for(int i = top;i<=bottom;i++)
                {
    //                list.add(matrix[i][left]);
                    matrix[i][left] = count;
                    count++;
                }
                left--;
                if(bottom<top||left<right)
                {
                    break;
                }
                for(int j = left;j>=right;j--)
                {
    //                list.add(matrix[bottom][j]);
                    matrix[bottom][j] = count;
                    count++;
                }
                bottom--;
                //Can be deleted
    /*          if(bottom<top||left<right)
                {
                    break;
                }
    */
                for(int i = bottom;i>=top;i--)
                {
    //                list.add(matrix[i][right]);
                    matrix[i][right] = count;
                    count++;
                }
                right++;
                if(bottom<top||left<right)
                {
                    break;
                }
            }
            return matrix;
        }
    }
    

Log in to reply
 

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