[LeetCode] 54 - Spiral Matrix
문제
- 링크: https://leetcode.com/problems/spiral-matrix
- 난이도: Medium
- 태그: 배열, 행렬, 시뮬레이션
- 결과:
Time: 0 ms (100.00%), Space: 9.3 MB (51.38%)
풀이
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int top = 0;
int bottom = m - 1;
int left = 0;
int right = n - 1;
vector<int> v;
v.reserve(m * n);
while(top <= bottom && left <= right)
{
// 오른쪽으로 이동
for (int i = left; i <= right; ++i)
{
v.push_back(matrix[top][i]);
}
top++;
// 아래쪽으로 이동
for (int i = top; i <= bottom; ++i)
{
v.push_back(matrix[i][right]);
}
right--;
// 왼쪽으로 이동
if (top <= bottom)
{
for (int i = right; i >= left; --i)
{
v.push_back(matrix[bottom][i]);
}
bottom--;
}
// 위쪽으로 이동
if (left <= right)
{
for (int i = bottom; i >= top; --i)
{
v.push_back(matrix[i][left]);
}
left++;
}
}
return v;
}
};
시뮬레이션 문제다. sprial order가 어떻게 진행되는지 패턴을 파악하는 것이 핵심이다. 사실은 그냥 범위를 좁혀가면서 왼쪽에서 오른쪽, 위에서 아래, 오른쪽에서 왼쪽, 아래에서 위 순서로 2차원 배열을 순회하는 것이다.
이 패턴에 맞게 구현하면 된다.
배운 점과 후기
나는 시뮬레이션이 싫어요
댓글남기기