#Leetcode# 59. Spiral Matrix II
Posted 丧心病狂工科女
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 59. Spiral Matrix II相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/spiral-matrix-ii/
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 ] ]
代码:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n, 0)); int up = 0, down = n - 1, left = 0, right = n - 1, val = 1; while (true) { for (int j = left; j <= right; ++j) res[up][j] = val++; if (++up > down) break; for (int i = up; i <= down; ++i) res[i][right] = val++; if (--right < left) break; for (int j = right; j >= left; --j) res[down][j] = val++; if (--down < up) break; for (int i = down; i >= up; --i) res[i][left] = val++; if (++left > right) break; } return res; } };
快一周不学习罪恶感 upup
FHFHFH
以上是关于#Leetcode# 59. Spiral Matrix II的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]59. Spiral Matrix II