zoukankan      html  css  js  c++  java
  • 【leetcode】Spiral Matrix II

    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:

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

    与Spiral Matrix相似,给定方阵的维度n,返回一个螺旋矩阵。

     1 class Solution {
     2 public:
     3     vector<vector<int> > generateMatrix(int n) {
     4         vector< vector<int> > matrix(n, vector<int>(n));
     5         //begin_row is the row number, end_row is the remaind size of each row
     6         int begin_row = 0, end_row = n - 1;
     7         //begin_col is the col number,end_col is the remaind size of each col
     8         int begin_col = 0, end_col = n - 1;
     9 
    10         int num = 1;
    11         while(true){
    12             for(int i = begin_row; i <= end_row; ++i)//left to right
    13                 matrix[begin_row][i] = num++;
    14             if(++begin_col > end_col) break;
    15 
    16             for(int i = begin_col; i <= end_col; ++i)//up to down
    17                  matrix[i][end_row] = num++;
    18             if(begin_row > --end_row) break;
    19 
    20             for(int i = end_row; i >= begin_row; --i)//right to left
    21                 matrix[end_col][i] = num++;
    22             if(begin_col > --end_col) break;
    23 
    24             for(int i = end_col; i >= begin_col; --i)//bottom to up
    25                 matrix[i][begin_row] = num++;
    26             if(++begin_row > end_row) break;
    27         }
    28 
    29         return matrix;
    30     }
    31 };
    View Code


  • 相关阅读:
    Xcode4快速Doxygen文档注释 — 简明图文教程(3分钟后爽歪歪)
    ACE小记
    【C++】获得本机所有网卡的IP和MAC地址信息(转)
    一周好文(11)
    cocos2d‘s replaceScene
    iPhone 真机调试安装流程
    金牌银牌铜牌
    整数分割(摘抄)

    马拦过河卒
  • 原文地址:https://www.cnblogs.com/zxy1992/p/4279001.html
Copyright © 2011-2022 走看看