From 94ae9c6dd28acab84b1f669c7ec0f7a764fd309c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= Date: Fri, 1 Feb 2019 21:34:40 +0800 Subject: [PATCH] Create 59. Spiral Matrix II.md --- solutions/59. Spiral Matrix II.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 solutions/59. Spiral Matrix II.md diff --git a/solutions/59. Spiral Matrix II.md b/solutions/59. Spiral Matrix II.md new file mode 100644 index 0000000..eccd8f9 --- /dev/null +++ b/solutions/59. Spiral Matrix II.md @@ -0,0 +1,23 @@ +# [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) +# 思路 +这题其实就是[54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix)的一个特例,54题没问题的话这题就一点问题没有了, +可参考[54题题解](https://github.com/ShusenTang/LeetCode/blob/master/solutions/54.%20Spiral%20Matrix.md)。 + +# C++ +``` C++ +class Solution { +public: + vector> generateMatrix(int n) { + vector>res(n, vector(n, 0)); + int num = 1; + for(int i = 0; i < n / 2; i++){ // 一共有 n / 2 圈(不包括中间的那一个元素) + for(int j = i; j <= n - i - 1; j++) res[i][j] = num++; + for(int j = i + 1; j <= n - i - 1; j++) res[j][n - i -1] = num++; + for(int j = n - i - 2; j >= i; j--) res[n - i - 1][j] = num++; + for(int j = n - i - 2; j >= i + 1; j--) res[j][i] = num++; + } + if(n % 2) res[n / 2][n / 2] = num; // 若n是奇数 + return res; + } +}; +```