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;j<y2;j++)
            {
                matrix[x1][j]=++k;
                System.out.println(matrix[x1][j]);
            }
            for(int i=x1;i<x2;i++)
            {
                matrix[i][y2]=++k;
                System.out.println(matrix[i][y2]);
            }
           
            for(int j=x2;j>x1;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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容