美文网首页LeetCode、剑指offer
【leetcode】59. Spiral Matrix II(螺

【leetcode】59. Spiral Matrix II(螺

作者: 邓泽军_3679 | 来源:发表于2019-05-11 17:08 被阅读0次

1、题目描述

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
  [ 1, 2, 3 ],
  [ 8, 9, 4 ],
  [ 7, 6, 5 ]
]

2、问题描述:

  • 螺旋填充一个矩阵。

3、问题关键:

4、C++代码:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
        if (!n) return res;
        int x = 0, y = 0, d = 0;
        for (int i = 0; i < n * n; i ++) {
            int a = x + dx[d], b = y + dy[d];
            if (a < 0 || a >= n || b < 0 || b >= n || res[a][b]) {
                d = (d + 1) % 4;
                a = x + dx[d], b = y + dy[d];
            }
            res[x][y] = i + 1;
            x = a, y = b;
        }
        return res;
    }
};

相关文章

网友评论

    本文标题:【leetcode】59. Spiral Matrix II(螺

    本文链接:https://www.haomeiwen.com/subject/oqtfaqtx.html