代码随想录_刷题 数列 59

  1. 螺旋矩阵 II
    · 循环不变量原则
    代码随想录_刷题 数列 59_第1张图片
int startx = 0, starty = 0, count = 1;
        int i = 0, j = 0;
        vector<vector<int>> a(n, vector<int>(n, 0));
        int loop = n / 2;
        int k = 1;
        while(loop--) {
            i = startx;
            j = starty;
            for(j = starty; j < n-k; j++) {
                a[startx][j] = count++;
            }
            for(i = startx; i < n-k; i++) {
                a[i][j] = count++;
            }
            for(; j > starty; --j) {
                a[i][j] = count++;
            }
            for(; i > startx; i--) {
                a[i][j] = count++;
            }
            startx = startx + 1;
            starty = starty + 1;
            k++;
        }
        if(n % 2) {
            a[n/2][n/2] = count;
        }
        return a;

你可能感兴趣的:(算法,c++)