第59题:螺旋矩阵 II

解题思路

59. 螺旋矩阵 II
该题54. 螺旋矩阵的思路是一样的。
每层都按红绿蓝紫的顺序把1~n^2依次添加进行
image.png

代码

class Solution {
    public static int[][] generateMatrix(int n) {
		int[][] matrix = new int[n][n];
		int value = 1;
		int row1 = 0, row2 = n-1;
		int col1 = 0, col2 = n-1;
		while(row1<=row2 && col1<=col2) {
        	for(int col = col1 ; col <= col2 ; col++) {  //将上面的行向右加入
        		matrix[row1][col] = value++;
        	}
        	for(int row = row1+1 ; row<=row2 ; row++) {   //将右边的列向下加入
        		matrix[row][col2] = value++;
        	}
        	if(row1<row2 && col1 < col2) {
        		for(int col = col2-1 ; col>col1 ;col--) {   //将下面的行向左加入
        			matrix[row2][col] = value++;
        		}
        		for(int row = row2 ; row>row1 ; row--) {    //将左边的列向上加入
        			matrix[row][col1] =value++;
        		}
        	}
        	row1++;
        	row2--;
        	col1++;
        	col2--;
        }
		return matrix;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值