美文网首页
LeetCode每日一题:spiral matrix ii

LeetCode每日一题:spiral matrix ii

作者: yoshino | 来源:发表于2017-06-07 10:07 被阅读21次

    问题描述

    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 int[][] generateMatrix(int n) {
            int[][] res = new int[n][n];
            int left = 0, right = n - 1, bottom = n - 1, top = 0, num = 1;
            while (left < right && top < bottom) {
                for (int i = left; i < right; i++) {
                    res[top][i] = num++;
                }
                for (int i = top; i < bottom; i++) {
                    res[i][right] = num++;
                }
                for (int i = right; i > left; i--) {
                    res[bottom][i] = num++;
                }
                for (int i = bottom; i > top; i--) {
                    res[i][left] = num++;
                }
                top++;
                bottom--;
                left++;
                right--;
            }
            if (n % 2 == 1) {
                res[n / 2][n / 2] = num;
            }
            return res;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:spiral matrix ii

          本文链接:https://www.haomeiwen.com/subject/xgsofxtx.html