【leetcode】59. 螺旋矩阵 II

题目:

给你一个正整数 n ,生成一个包含 1 到 n 2 n^2 n2 所有元素,且元素按顺时针顺序螺旋排列的 n × n n \times n n×n 正方形矩阵 matrix

代码:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        // dir[0], {0, 1} 向右移动
        // dir[1], {1, 0} 向下移动
        // dir[2], {0, -1} 向左移动
        // dir[3], {-1, 0} 向上移动
        int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};       // 方向数组
        vector<vector<int>> matrix(n, vector<int>(n, 0)); // 初始化矩阵
        int row = 0, col = 0;              // 标记当前位置的横纵坐标
        int rec = -1;                      // 标记当前方向
        for (int k = 1; k <= n * n; k++) { // 枚举数字
            matrix[row][col] = k;
            if (rec != -1) { // 判断是否能够继续原有方向移动
                int tx = row + dir[rec][0]; // 下个位置的横坐标
                int ty = col + dir[rec][1]; // 下个位置的纵坐标
                if (0 <= tx && tx < n && 0 <= ty && ty < n && matrix[tx][ty] == 0) { // 判断移动的下个位置是否合法
                    row = tx;
                    col = ty;
                    continue;
                }
            }
            for (int t = 0; t < 4; t++) { // 按照右/下/上/左的顺序进行移动
                int tx = row + dir[t][0];
                int ty = col + dir[t][1];
                if (0 <= tx && tx < n && 0 <= ty && ty < n && matrix[tx][ty]) {
                    row = tx;
                    col = ty;
                    rec = t; // 记录当前移动方向
                    break;
                }
            }
        }
        return matrix;
    }
};
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值