【二维数组遍历填充】

链接:59. 螺旋矩阵 II - 力扣(LeetCode)

题目描述:

注意事项:如果是一个方阵,可以直接定义遍历的圈数,并且如果是奇数的话,需要对圆圈中间的数做填充所补充;

    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> matrix(n, vector<int>(n));
        int loop = n/2;
        int startx = 0, starty = 0;
        int i,j, offset = 1, count = 1;
        while (loop--) {
            i = startx;
            j = starty;
            for (j = starty; j < n - offset; j++) {
                matrix[i][j] = count;
                count += 1;
            }
            for (i = startx; i < n - offset; i++) {
                matrix[i][j] = count;
                count += 1;
            }
            for (; j > starty; j--) {
                matrix[i][j] = count;
                count += 1;
            }
            for (; i > startx; i--) {
                matrix[i][j] = count;
                count += 1;
            }
            offset += 1;
            startx++;
            starty++;
        }
        if (n%2 == 1) matrix[n/2][n/2] = count;
        return matrix;
    }

链接:https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/description/

题目描述:

注意事项:

  1. 如果是方阵,不能通过圈数来作为循环停止的标志;
  2. 根据循环停止的条件,最后一行或者最后一列是不能被遍历到,需要单独处理;
    vector<int> spiralArray(vector<vector<int>>& array) {
        vector<int> result;
        if (array.size() == 0) return result;
        int top = 0, bottom = array.size() - 1;
        
        int left = 0, right = array[0].size() - 1;
        while (left < right && top < bottom) {
            for (int i = left; i < right; i++) result.push_back(array[top][i]);
            for (int i = top; i < bottom; i++) result.push_back(array[i][right]);
            for (int i = right; i > left; i--) result.push_back(array[bottom][i]);
            for (int i = bottom; i > top; i--) result.push_back(array[i][left]);
            top++;
            right--;
            bottom--;
            left++;
        }
        if (left == right) {
            for (int i = top; i <= bottom; i++) result.push_back(array[i][left]);
        }else if (top == bottom) {
            for (int i = left; i <= right; i++) result.push_back(array[top][i]);
        }
        return result;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨主任o_o

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值