算法分析与设计课程——LeetCode刷题之 Spiral Matrix
2018-01-07 14:19
441 查看
题目:
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:
You should return
答案:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<vector<int> > dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector<int> res;
int nr = matrix.size(); if (nr == 0) return res;
int nc = matrix[0].size(); if (nc == 0) return res;
vector<int> nSteps{nc, nr-1};
int iDir = 0; // index of direction.
int ir = 0, ic = -1; // initial position
while (nSteps[iDir%2]) {
for (int i = 0; i < nSteps[iDir%2]; ++i) {
ir += dirs[iDir][0]; ic += dirs[iDir][1];
res.push_back(matrix[ir][ic]);
}
nSteps[iDir%2]--;
iDir = (iDir + 1) % 4;
}
return res;
}
};
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].
答案:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<vector<int> > dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector<int> res;
int nr = matrix.size(); if (nr == 0) return res;
int nc = matrix[0].size(); if (nc == 0) return res;
vector<int> nSteps{nc, nr-1};
int iDir = 0; // index of direction.
int ir = 0, ic = -1; // initial position
while (nSteps[iDir%2]) {
for (int i = 0; i < nSteps[iDir%2]; ++i) {
ir += dirs[iDir][0]; ic += dirs[iDir][1];
res.push_back(matrix[ir][ic]);
}
nSteps[iDir%2]--;
iDir = (iDir + 1) % 4;
}
return res;
}
};
相关文章推荐
- 算法分析与设计课程(17):【leetcode】4Sum
- 算法分析与设计课程——LeetCode刷题之 Rotate Image
- 算法分析与设计课程——LeetCode刷题之Reverse Integer
- 算法分析与设计课程——LeetCode刷题之 Merge k Sorted Lists
- 算法分析与设计课程(5):【leetcode】Search for a Range
- 算法分析与设计课程——LeetCode刷题之Search for a Range
- 算法分析与设计课程——LeetCode刷题之4Sum
- 算法分析与设计课程(10):【leetcode】Simplify Path
- 算法分析与设计课程——LeetCode刷题之Merge Two Sorted Lists
- 算法分析与设计课程(15):【leetcode】 Find Minimum in Rotated Sorted Array
- 算法分析与设计课程(16):【leetcode】 Integer to Roman
- 算法分析与设计课程(18):【leetcode】Clone Graph
- 算法分析与设计课程(7):【leetcode】Reverse Nodes in k-Group
- 算法分析与设计课程(3):【leetcode】Permutations
- 算法分析与设计课程(6):【leetcode】Sudoku
- 算法分析与设计课程——LeetCode刷题之 Pow(x, n)
- 算法分析与设计课程(12):【leetcode】 Count Complete Tree Nodes
- 算法分析与设计课程——LeetCode刷题之Valid Parentheses
- 算法分析与设计课程06——542. 01 Matrix(Medium)
- [算法分析与设计] leetcode 每周一题: Set Matrix Zeroes