We can modify the implementation based on the idea above. We can track the rowBegin, rowEnd, colBegin and colEnd. After scanning a row/column, we update the one of these four variables such that we can avoid duplicates.
1: class Solution {
2: public:
3: vector<int> spiralOrder(vector<vector<int>>& matrix) {
4: vector<int> res;
5: if (matrix.size() == 0) return res;
6: int rows = matrix.size();
7: int cols = matrix[0].size();
8: int rowBegin = 0, rowEnd = rows-1;
9: int colBegin = 0, colEnd = cols-1;
10: while (rowBegin <= rowEnd && colBegin <= colEnd) {
11: for (int j = colBegin; j <= colEnd; j++) res.push_back(matrix[rowBegin][j]);
12: rowBegin++;
13: for (int i = rowBegin; i <= rowEnd; i++) res.push_back(matrix[i][colEnd]);
14: colEnd--;
15: if (rowBegin <= rowEnd) {
16: for (int j = colEnd; j >= colBegin; j--) res.push_back(matrix[rowEnd][j]);
17: rowEnd--;
18: }
19: if (colBegin <= colEnd) {
20: for (int i = rowEnd; i >= rowBegin; i--) res.push_back(matrix[i][colBegin]);
21: colBegin++;
22: }
23: }
24: return res;
25: }
26: };
No comments:
Post a Comment