59. 螺旋矩阵 II

1.方法一:

 

/*
思路:定义上下左右边界,模拟循环转圈,需要注意最后只剩一行或一列的时候需要添加额外的判断
因为每次都是先往右走和先往下走,所以往右走和往下走的路一定是没走过的路,不需要加 if 判断;往左走的时候,如果 top == bottom,那么会重复走之前从左往右走过的路,所以需要加上 top < bottom 的判断,同理往上走也一样。
*/

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        //if(n == 0) return {[]};
        int left = 0, right = n - 1;
        int top = 0, bottom = n - 1;
        int count = 1;
        vector<vector<int>> result(n, vector<int>(n, 0));
        while(left <= right && top <= bottom){
            for(int colum = left; colum <= right; colum++){
                result[top][colum] = count++;
            }

            for(int row = top + 1; row <= bottom; row++){
                result[row][right] = count++;
            }

            if(left < right && top < bottom){
                for(int colum = right - 1; colum > left; colum--){
                    result[bottom][colum]= count++;
                }

                for(int row = bottom; row > top; row--){
                    result[row][left]= count++;
                }
            }
            left++, right--;
            top++, bottom--;
        }
        return result;
    }
};

2. 方法二:

坚持循环不变量:

 

  • 填充上行从左到右
  • 填充右列从上到下
  • 填充下行从右到左
  • 填充左列从下到上

 

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> result(n, vector<int>(n,0));
        int startx = 0, starty = 0;
        int i, j;
        int count = 1;
        int offset = 1;
        int loop = n /2;
        int mid = n / 2;

        while(loop--){
            i = startx;
            j = starty;
            //从左到右
            for(; j < n - offset; j++){
                result[i][j] = count++;
            }
            //从上到下
            for(; i < n - offset; i++){
                result[i][j] = count++;
            }

            //从右到左
            for(; j > starty; j--){
                result[i][j] = count++;
            }

            //从下到上
            for(; i > startx; i--){
                result[i][j] = count++;
            }
            startx++;
            starty++;
            offset += 1;
        }
        if(n % 2 == 1) result[mid][mid] = count;
        return result;

    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值