设为首页 加入收藏

TOP

leetcode - Spiral Matrix II
2015-07-20 17:26:59 来源: 作者: 【 】 浏览:3
Tags:leetcode Spiral Matrix

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

class Solution {
public:
    std::vector
  
    > generateMatrix(int n) {
		std::vector
   
    > matrix(n,std::vector
    
     (n,0)); int start = 0, end = n - 1; int step = 1; while(start < end) { for (int i = start; i < end; i++) { matrix[start][i] = step++; } for (int i = start; i < end; i++) { matrix[i][end] = step++; } for(int i = end; i > start; i--) { matrix[end][i] = step++; } for(int i = end; i > start; i--) { matrix[i][start] = step++; } start++; end--; } if(start == end) { matrix[start][end] = step++; } return matrix; } };
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[HDU 1427]速算24点(DFS暴搜) 下一篇POJ 3602 Typographical Ligatures

评论

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

·About - Redis (2025-12-26 08:20:56)
·Redis: A Comprehens (2025-12-26 08:20:53)
·Redis - The Real-ti (2025-12-26 08:20:50)
·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)