59. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2
in spiral order.
For example,Given n =3,
You should return the following matrix:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int t=n;
        if(n<=0)
          return matrix;
        
        int x1 = 0,y1 = 0;
        int k = 0;
        while(n>=2)
        {
            int x2 = x1+n-1;
            int y2 = y1+n-1;
            
            for(int j=y1;jx1;j--)
            {
                matrix[x2][j]=++k;
                System.out.println(matrix[x2][j]);
            }
            
            for(int i=y2;i>y1;i--)
            {
                matrix[i][y1]=++k;
                System.out.println(matrix[i][y1]);
            }
            
            x1++;
            y1++;
            n -= 2;
            
        }
        System.out.println(n);
        if(n==1)
           matrix[t/2][t/2] = t*t;
        return matrix;
    }
}

你可能感兴趣的:(59. Spiral Matrix II)