leetcode 59. Spiral Matrix II


Given a positive integern, generate a square matrix filled with elements from 1 ton2in 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         vector<vector<int> > res(n, vector<int>(n, 0));
 5         int res[n][n];
 6         int **res = new int* [n];
 7         for (int i = 0; i < n; i++)
 8             
 9         int num = n * n;
10         int cnt = 1;
11         int start_row = 0, start_col = 0, end_row = n - 1, end_col = n - 1; 
12         while (cnt <= num) {
13             for (int j = start_col; j <= end_col; j++) {
14                 res[start_row][j] = cnt++;
15             }
16             for (int i = start_row + 1; i <= end_row; i++) {
17                 res[i][end_col] = cnt++;
18             }
19             for (int j = end_col - 1; j >= start_col; j--) {
20                 res[end_row][j] = cnt++;
21             }
22             for (int i = end_row - 1; i > start_row; i--) {
23                 res[i][start_col] = cnt++;
24             }
25             start_row++;
26             start_col++;
27             end_row--;
28             end_col--;
29         }
30         return res;
31     }
32 };

优质内容筛选与推荐>>
1、hashlib模块
2、js参数传递
3、#HTTP协议学习# (六)代理
4、Android popupwindow 示例程序一
5、PHP与MYSQL事务处理


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号