设为首页 加入收藏

TOP

Leetcode 细节实现题 Spiral Matrix II
2015-07-20 17:46:56 来源: 作者: 【 】 浏览:2
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 打印全..

评论

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

·如何在 C 语言中管理 (2025-12-25 03:20:14)
·C语言和内存管理有什 (2025-12-25 03:20:11)
·为什么C语言从不被淘 (2025-12-25 03:20:08)
·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)