19.2.9 [LeetCode 59] 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 ]
]
 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

 

posted @ 2019-02-09 15:41  TobicYAL  阅读(386)  评论(0编辑  收藏  举报