Spiral Matrix I(II)
来源:互联网 发布:苹果手机mac怎么修改 编辑:程序博客网 时间:2024/05/22 04:34
题目一:螺旋序矩阵
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
You should return [1,2,3,6,9,8,7,4,5]
.
思路
注意一些边界情况。
maxlevel = min(row,col)/2+min(row,col)%2;
这个也要注意。
class Solution {public: vector<int> spiralOrder(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> result; int row = matrix.size(); if(row<=0) return result; int col = matrix[0].size(); if(col==1){ for(int i=0;i<row;i++) result.push_back(matrix[i][0]); return result; } int level = 0; int maxlevel = min(row,col)/2+min(row,col)%2; while(level<maxlevel) { for(int j=level;j<=col-1-level;j++){ result.push_back(matrix[level][j]); } for(int i=level+1;i<row-1-level;i++){ result.push_back(matrix[i][col-1-level]); } if(row-1-level==level) break; for(int j=col-1-level;j>level;j--){ result.push_back(matrix[row-1-level][j]); } for(int i=row-1-level;i>level;i--){ result.push_back(matrix[i][level]); } level++; } return result; }};
还可以用递归的方法。
题目二:Spiral Matrix II
class Solution {public: vector<vector<int> > generateMatrix(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int>> result(n,vector<int>(n,0)); if(n<=0) return result; int cur = 1; int level = 0; int maxlevel = n/2+n%2; while(level<maxlevel) { for(int j=level;j<=n-1-level;j++){ result[level][j] = cur++; } for(int i=level+1;i<n-1-level;i++){ result[i][n-1-level] = cur++; } if(n-1-level==level) break; for(int j=n-1-level;j>level;j--){ result[n-1-level][j] = cur++; } for(int i=n-1-level;i>level;i--){ result[i][level] = cur++; } level++; } return result; } };
- Spiral Matrix I(II)
- spiral-matrix I&II
- Spiral Matrix I && Spiral Matrix II
- [LeetCode]Spiral Matrix I & II & Rotate Matrix
- LeetCode题解:Spiral Matrix I and II
- 旋转数组 I & II Spiral Matrix
- [LeetCode]-Spiral Matrix I&II 螺旋矩阵
- LeetCode - Spiral Matrix I && II - Frequent
- LeetCode54/59 Spiral Matrix I/II
- LeetCode(54)(59) Spiral Matrix I II
- LeetCode 54/59. Spiral Matrix i, ii
- 54 59. Spiral Matrix I II
- Spiral Matrix && Spiral Matrix II
- leetcode 之Spiral Matrix I 和 II 解题思路
- leetcode -- Spiral Matrix I&II -- 简单,但需要优化
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- java jREX
- sc.next() 和 nextLine 的区别
- MFC控件(7):Split Button
- Hibernate学习总结
- iOS: NSObject的方法conformsToProtocol:
- Spiral Matrix I(II)
- 素数表(Eratosthenes)
- 创建二叉搜索树算法
- C语言小程序(四)、杨辉三角
- (转)通过Stratus 服务器在Flash Player中使用RTMFP 开发
- 今天的面试一个人的感想
- Hiberation 总结
- linux特殊符号大全
- 对H264进行RTP封包原理