LeetCode:Spiral Matrix II - 将元素1-n^2以螺旋序填充到矩阵

1、题目名称

Spiral Matrix(螺旋输出矩阵中的元素)

2、题目地址

https://leetcode.com/problems/spiral-matrix-ii/

3、题目内容

英文:Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

中文:给出一个整数n,生成一个矩阵,使用数字1到n^2以螺旋顺序填充这个矩阵

例如:给出n=3,则生成如下矩阵:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

4、解题方法1

做这道题的方式可以参考SpiralMatrix,遍历顺序是一样的,只不过SpiralMatrix是取数,这道题要做的是赋值。

Java代码如下:

/**
 * @功能说明:LeetCode 59 - Spiral Matrix II
 * @开发人员:Tsybius2014
 * @开发时间:2015年11月3日
 */
public class Solution {
    
    /**
     * 生成矩阵
     * @param n
     * @return
     */
    public int[][] generateMatrix(int n) {
        
        if (n < 0) {
            n = 0;
        }
        
        int[][] matrix = new int[n][n];
        if (n == 0) {
            return matrix;
        }
        
        int counter = 1;
        
        //左右上下四个边界
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;

        int i;
        while (true) {
             
            //上边,自左至右
            for (i = left; i <= right; i++) {
                matrix[top][i] = counter++;
            }
            if (++top > bottom) {
                break;
            }
             
            //右边,自上至下
            for (i = top; i <= bottom; i++) {
                matrix[i][right] = counter++;
            }
            if (left > --right) {
                break;
            }
             
            //下边,自右至左
            for (i = right; i >= left; i--) {
                matrix[bottom][i] = counter++;
            }
            if (top > --bottom) {
                break;
            }
             
            //左边,自下至上
            for (i = bottom; i >= top; i--) {
                matrix[i][left] = counter++;
            }
            if (++left > right) {
                break;
            }
        }
        
        return matrix;
    }
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/525517

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值