Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
문제 풀이:
구현문제 - 아래 그림대로 구현한다.
맨 위 row와 오른쪽 col을 돌고 아래 row와 왼쪽 col를 돈다.
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> answer;
int n = matrix.size();
if(n==0){
return answer;
}
int r1=0, r2=n-1;
int m = matrix[0].size();
if(m == 0){
for(int i=0; i<n; i++){
answer.push_back(matrix[n][0]);
}
return answer;
}
int c1=0, c2=m-1;
while(r1<=r2 && c1<=c2){
for(int c = c1; c<=c2; c++)
answer.push_back(matrix[r1][c]);
for(int r = r1+1; r<=r2; r++)
answer.push_back(matrix[r][c2]);
if(r1 < r2 && c1 < c2){
for(int c = c2-1; c>c1; c--)
answer.push_back(matrix[r2][c]);
for(int r = r2; r>r1; r--)
answer.push_back(matrix[r][c1]);
}
r1++;
r2--;
c1++;
c2--;
}
return answer;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 34] Find First and Last Position of Element in Sorted Array (0) | 2020.11.12 |
---|---|
[leetcode 23] Merge k Sorted Lists (0) | 2020.11.12 |
[leetcode 28] Implement strStr() (0) | 2020.11.10 |
[leetcode 42] Trapping Rain Water (0) | 2020.11.10 |
[leetcode 48] Rotate Image (0) | 2020.11.09 |
댓글