• Leetcode59. Spiral Matrix II螺旋矩阵2


    给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

    示例:

    输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]

    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n)
        {
            vector<vector<int> > res(n, vector<int>(n, 0));
            int left = 0;
            int up = 0;
            int right = n - 1;
            int down = n - 1;
            int cnt = 1;
            while(up <= down && left <= right)
            {
                for(int i = left; i <= right; i++)
                    res[up][i] = cnt++;
                up++;
                if(up > down)
                    break;
                for(int i = up; i <= down; i++)
                    res[i][right] = cnt++;
                right--;
                if(left > right)
                    break;
                for(int i = right; i >= left; i--)
                    res[down][i] = cnt++;
                down--;
                if(up > down)
                    break;
                for(int i = down; i >= up; i--)
                    res[i][left] = cnt++;
                left++;
                if(left > right)
                    break;
            }
            return res;
        }
    };
  • 相关阅读:
    嵊州D1T2 圣女
    嵊州D1T1 总统先生,一路走好!
    第三节暑期信息奥赛课——图论
    并查集小结
    洛谷P1003 铺地毯 noip2011提高组day1T1
    洛谷p1216 IOI1994 Day1T1
    Title
    Title
    Title
    Title
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433863.html
Copyright © 2020-2023  润新知