Loading

Leetcode-59-螺旋矩阵

题目链接


题目描述

正整数 n ,生成一个 1 到 \(n^2\) 所有元素,且按顺时针顺序螺旋排列的正方形矩阵。

思路

(row, col) 表示要矩阵的坐标。

  1. (0, 0) 位置开始,依次按 右-下-左-上 的顺序插入元素
  2. 定义一个表示方向的数组 d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
  3. 下一个坐标的计算方式:(row+d[dIndex][0], col+d[dIndex][1])
  4. 当下个坐标位置不合法时, 更新dIndex,开始下个方向的插入。

C++代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> m(n, vector<int>(n));

        int cnt = n*n;

        // 设置方向 右下左上
        int d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
        int dIndex = 0, tc, tr;
        int row = 0, col = 0;

        for (int i = 1; i <= cnt; i++) {
            m[row][col] = i;

            // 判断当前方向下一个位置是否合法
            tr = row+d[dIndex][0];
            tc = col+d[dIndex][1];
            if (tr==n || tc==n || tc==-1 || m[tr][tc])  // 若不合理 更新方向
                dIndex = (dIndex+1) % 4;

            // 下一个位置
            row = row+d[dIndex][0];
            col = col+d[dIndex][1];
        }

        return m;
    }
};
posted @ 2022-01-12 12:35  ARUI丶  阅读(41)  评论(0)    收藏  举报