leetcode数组专项习题:螺旋矩阵-II

版权声明:本文为博主原创,未经允许请不要转载哦 https://blog.csdn.net/weixin_43277507/article/details/88174995

13、螺旋矩阵-II
spiral-matrix: Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
For example,
Given n =3, You should return the following matrix:
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
题设要求:给定整数n,以螺旋顺序生成填充有1到n^2的元素的方阵。
分析:和螺旋矩阵-I的题目相比

https://blog.csdn.net/weixin_43277507/article/details/88170604

,个人感觉II更简单一些。总体思路差不多,不再赘述。
代码如下:

public class Solution{
    public static void main(String[] args) 
    {
    	Solution sl = new Solution();
    	int n = 3;
        int[][] matrix= sl.generateMatrix(n);
        for(int i=0;i<n;i++)
        {
        	for(int j=0;j<n;j++)
        	{
        		System.out.print(matrix[i][j]+" ");
        	}
        	System.out.println("");
        }
     }
     
    public int[][] generateMatrix(int n) 
    {
        int[][] generateMatrix = new int[n][n];   
        int loop=(n+1)/2;
        int j=1;
        for(int i=0;i<loop;i++,n-=2)
        {
        	for(int col=i;col<i+n;col++)
        	{
        		generateMatrix[i][col]=j;
        		j++;
        	}
        	for(int row=i+1;row<i+n;row++)
        	{
        		generateMatrix[row][i+n-1]=j;
        		j++;
        	}
        	for(int col=i+n-2;col>=i;col--)
        	{
        		generateMatrix[i+n-1][col]=j;
        		j++;
        	}
        	for(int row=i+n-2;row>i;row--)
        	{
        		generateMatrix[row][i]=j;
        		j++;
        	}
        }
        return generateMatrix;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88174995