首页 > 其他 > 详细

19.2.9 [LeetCode 59] Spiral Matrix II

时间:2019-02-09 16:09:42      阅读:176      评论:0      收藏:0      [点我收藏+]

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 ]
]
技术分享图片
 1 class Solution {
 2 public:
 3     vector<vector<int>> generateMatrix(int n) {
 4         int dir[4][2] = { 0,1,1,0,0,-1,-1,0 }, dire = 0, x = 0, y = 0;
 5         vector<vector<int>>ans(n, vector<int>(n, -1));
 6         for (int i = 1; i <= (n * n); i++) {
 7             ans[x][y] = i;
 8             int nextx = x + dir[dire][0], nexty = y + dir[dire][1];
 9             if (nextx >= n || nextx < 0 || nexty >= n || nexty < 0 || ans[nextx][nexty] != -1) {
10                 dire = (dire + 1) % 4;
11                 nextx=x+dir[dire][0], nexty = y + dir[dire][1];
12             }
13             x = nextx, y = nexty;
14         }
15         return ans;
16     }
17 };
View Code

 

19.2.9 [LeetCode 59] Spiral Matrix II

原文:https://www.cnblogs.com/yalphait/p/10357555.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!