螺旋矩阵II(leetcode 59)

转圈过程(边界处理)遵循循环不变量的原则,坚持一个原则处理每一条边,左闭右开处理

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> num(n, vector<int>(n, 0));
        int startx = 0;
        int starty = 0;
        int offset = 1;
        int count = 1;
        int loop = n/2;
        int i;
        int j;
        while(loop --)
        {
            
            for( j = starty; j < n - offset; j++)
            {
                num[startx][j] = count;
                count ++;
            }
            for( i = startx; i < n - offset; i++)
            {
                num[i][j] = count;
                count ++;
            }
            for( ; j > starty; j--)
            {
                num[i][j] = count;
                count ++;
            }
            for( ; i > startx; i--)
            {
                num[i][j] = count;
                count ++;
            }
            startx++;
            starty++;
            offset++;
        }
        if(n % 2)
        {
            num[n/2][n/2] = count;
        }
        return num;
    }
};
相关推荐
白兰地空瓶1 分钟前
你以为树只是画图?不——它是算法面试的“隐形主角”
前端·javascript·算法
好易学·数据结构11 分钟前
可视化图解算法74:最小花费爬楼梯
数据结构·算法·leetcode·动态规划·力扣
Maỿbe36 分钟前
力扣hot图论部分
算法·leetcode·图论
LYFlied44 分钟前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌1 小时前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
子枫秋月1 小时前
C++字符串操作与迭代器解析
数据结构·算法
鹿角片ljp1 小时前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
(●—●)橘子……1 小时前
记力扣1471.数组中的k个最强值 练习理解
数据结构·python·学习·算法·leetcode
oioihoii1 小时前
C++共享内存小白入门指南
java·c++·算法
Bruce_kaizy1 小时前
c++图论————图的基本与遍历
c++·算法·图论