zoukankan      html  css  js  c++  java
  • LeetCode59 Spiral Matrix II

    题目:

    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example,
    Given n = 3,

    You should return the following matrix: (Medium)

    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]
    

    分析:

    跟 Sprial Matrix I处理方式一样,先建立好n * n的数组,然后按照顺时针顺序填入数字即可。

    代码:

     1 class Solution {
     2 public:
     3     vector<vector<int>> generateMatrix(int n) {
     4         vector<vector<int>> result(n, vector<int>(n,0));
     5         int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1;
     6         int count = 1;
     7         while (rowBegin <= rowEnd && colBegin <= colEnd) {
     8             for (int i = colBegin; i <= colEnd; ++i ) {
     9                 result[rowBegin][i] = count;
    10                 count++;
    11             }
    12             rowBegin++;
    13             if (rowBegin > rowEnd) {
    14                 break;
    15             }
    16             for (int i = rowBegin; i <= rowEnd; ++i) {
    17                 result[i][colEnd] = count;
    18                 count++;
    19             }
    20             colEnd--;
    21             if (colBegin > colEnd) {
    22                 break;
    23             }
    24             for (int i = colEnd; i >= colBegin; --i) {
    25                 result[rowEnd][i] = count;
    26                 count++;
    27             }
    28             rowEnd--;
    29             if (rowBegin > rowEnd) {
    30                 break;
    31             }
    32             for (int i = rowEnd; i>= rowBegin; --i) {
    33                 result[i][colBegin] = count;
    34                 count++;
    35             }
    36             colBegin++;
    37         }
    38         return result;
    39     }
    40 };
  • 相关阅读:
    LeetCode 21. 合并两个有序链表
    LeetCode 20. 有效的括号
    LeetCode 19. 删除链表的倒数第N个节点
    AI
    http
    IP地址
    wiodows /linux CMD
    git
    AI
    JS常用的获取值和设值的方法
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5886924.html
Copyright © 2011-2022 走看看