Notice
250x250
Recent Posts
Recent Comments
Link
넘치게 채우기
[LeetCode] 54. Spiral Matrix 본문
728x90
반응형
https://leetcode.com/problems/spiral-matrix/description/
문제 유형 : 나선형 매트릭스
난이도 : Medium
문제
Given an m x n matrix, return all elements of the matrix in spiral order.
m X n의 매트릭스를 나선형으로 순회한 순서로 반환해라.
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
풀이
오른쪽으로 순회 -> 아래로 순회 -> 왼쪽으로 순회 -> 위로 순회를 반복한다.
한번 순회할 때 구역을 [시작, 끝)으로 했다. (시작부분을 제외하고 끝부분을 포함한 순회)
그리고 [0, 0] 지점은 순회하기 전부터 넣는식으로 했다.
코드(C++)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<int> result;
int row = 0;
int col = 0;
int loop = 0;
int cnt = 0;
int goal = m*n;
result.push_back(matrix[0][0]);
cnt++;
while (goal > cnt) {
// Move right
col++;
for (int i = col; i < n; i++) {
result.push_back(matrix[row][i]);
cnt++;
}
row++;
n--;
col = n;
if(goal <= cnt) break;
// Move down
for (int i = row; i < m; i++) {
result.push_back(matrix[i][col]);
cnt++;
}
m--;
row = m;
if (goal <= cnt) break;
col--;
// Move left
for (int i = col; i >= loop; i--) {
result.push_back(matrix[row][i]);
cnt++;
}
if (goal <= cnt) break;
row--;
col = loop;
// Move up
for (int i = row; i >= loop + 1; i--) {
result.push_back(matrix[i][col]);
cnt++;
}
row = loop+1;
loop++;
}
return result;
}
};
728x90
반응형
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 59. Spiral Matrix II (0) | 2023.05.10 |
---|---|
[LeetCode] 4. Median of Two Sorted Arrays (0) | 2023.05.09 |
[LeetCode] 1572. Matrix Diagonal Sum (0) | 2023.05.08 |
[LeetCode] 1498. Number of Subsequences That Satisfy the Given Sum Condition (0) | 2023.05.07 |
[LeetCode] 1456. Maximum Number of Vowels in a Substring of Given Length (0) | 2023.05.07 |