Leetcode 59. Spiral Matrix II (Medium) (cpp)
2016-07-27 15:08
375 查看
Leetcode 59. Spiral Matrix II (Medium) (cpp)
Tag: Array
Difficulty: Medium
Tag: Array
Difficulty: Medium
/* 59. Spiral Matrix II (Medium) 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: vector<vector<int>> generateMatrix(int n) { if (n <1) return {}; vector<vector<int>> res(n, vector<int>(n)); int i = n - 1, j = n - 1, k = 1, h = 0, l = 0; while (k <= n * n) { for (int col = l; col <= j; col++) res[h][col] = k++; if (++h > i) break; for (int row = h; row <= i; row++) res[row][j] = k++; if (--j < l) break; for (int col = j; col >= l; col--) res[i][col] = k++; if (--i < h) break; for (int row = i; row >= h; row--) res[row][l] = k++; if (++l > j) break; } return res; } };
相关文章推荐
- c++ 内存管理
- C++拷贝构造函数详解
- 错误:fatal error C1189: #error : The C++ Standard Library forbids macroizing keywords. Enable warning
- 5-31 笛卡尔树
- Leetcode 54. Spiral Matrix (Medium) (cpp)
- 一个项目调用另一个项目中的函数
- 转载一份C++线程池的代码,非常实用
- eclipse3.5(C++&Java)使用教程
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- GDI+初始化类
- 拓扑排序算法
- RVO V.S. std::move
- c文件操作函数
- C++11 左值、右值、右值引用详解