[LeetCode] 105: Spiral Matrix
来源:互联网 发布:布拉格之春 知乎 编辑:程序博客网 时间:2024/05/22 10:36
[Problem]
[Solution]
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]
.
[Solution]
class Solution {说明:版权所有,转载请注明出处。Coder007的博客
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> res;
// invalid
if(matrix.size() == 0 || matrix[0].size() == 0)return res;
// initial bound
int upper = 0, bottom = matrix.size(), left = -1, right = matrix[0].size();
int i = 0, j = 0, direct = 0;// 0: right, 1: down, 2: left, 3: up
while(res.size() < matrix.size() * matrix[0].size()){
res.push_back(matrix[i][j]);
if(direct == 0){
if(j+1 == right){
right--;
i++;
direct = 1;
}
else{
j++;
}
}
else if(direct == 1){
if(i+1 == bottom){
bottom--;
j--;
direct = 2;
}
else{
i++;
}
}
else if(direct == 2){
if(j-1 == left){
left++;
i--;
direct = 3;
}
else{
j--;
}
}
else if(direct == 3){
if(i-1 == upper){
upper++;
j++;
direct = 0;
}
else{
i--;
}
}
}
return res;
}
};
阅读全文
0 0
- [LeetCode] 105: Spiral Matrix
- [leetcode]Spiral Matrix&&Spiral Matrix II
- Leetcode:Spiral Matrix与Spiral Matrix II
- LeetCode | Spiral Matrix /Spiral Matrix II
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix
- [Leetcode] Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode] Spiral Matrix
- leetcode 80: Spiral Matrix
- [Leetcode] Spiral Matrix
- [LeetCode]Spiral Matrix
- [LeetCode] 101: Simplify Path
- [LeetCode] 102: Single Number
- [LeetCode] 103: Single Number II
- photoshop下载教程
- [LeetCode] 104: Sort Colors
- [LeetCode] 105: Spiral Matrix
- [LeetCode] 106: Spiral Matrix II
- [LeetCode] 107: Sqrt(x)
- [LeetCode] 108: String to Integer
- [LeetCode] 109: Subsets
- [LeetCode] 110: Subsets II
- [LeetCode] 111: Substring with Concatenation of All Words
- 汇编语言学习(一)
- [LeetCode] 112: Sudoku Solver