LeetCode、剑指offer

【leetcode】59. Spiral Matrix II(螺

2019-05-11  本文已影响0人  邓泽军_3679

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;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读