设为首页 加入收藏

TOP

Leetcode 细节实现题 Spiral Matrix II
2015-07-20 17:46:56 来源: 作者: 【 】 浏览:1
Tags:Leetcode 细节 实现 Spiral Matrix

Spiral Matrix II

Total Accepted: 12773 Total Submissions: 41526My Submissions

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 ]
]


题意:将数值 1 到n^2以螺旋顺序放到到一个方阵中
思路:
从左到右,从上到下,从右到左,从下到上按顺序遍历放数值
将矩阵的(0,0)元素看成坐标原点,向右为x轴正方向,向下为y轴正方向
用四个变量,即两个坐标(startx, starty), (endx, endy) 表示每轮遍历的矩阵的左上角和右下角的坐标
复杂度:O(n^2)

vector
  
    > generateMatrix(int n){
	vector
   
     > matrix(n, vector
    
     (n)); int startx = 0, starty = 0; int endx = n - 1, endy = n - 1; for(int k = 1; k <= n * n; ){ for(int j = startx; j <= endx; ++j) matrix[starty][j] = k++; starty++; for(int i = starty; i <= endy; ++i) matrix[i][endy] = k++; endx--; for(int j = endx; j >= startx; --j) matrix[endy][j] = k++; endy--; for(int i = endy; i >= starty; --i) matrix[i][startx] = k++; startx++; } return matrix; }
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇《Effective C++》学习笔记(八) 下一篇CF459C Pashmak and Buses 打印全..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·哈希表 - 菜鸟教程 (2025-12-24 20:18:55)
·MySQL存储引擎InnoDB (2025-12-24 20:18:53)
·索引堆及其优化 - 菜 (2025-12-24 20:18:50)
·Shell 中各种括号的 (2025-12-24 19:50:39)
·Shell 变量 - 菜鸟教 (2025-12-24 19:50:37)