|
| 1 | +/** |
| 2 | + * 풀이 |
| 3 | + * - 탐색 방향을 90도씩 회전해나가면서 주어진 2차원 배열 matrix를 탐색합니다 |
| 4 | + * - 한계: 주어진 matrix를 변형하게 되며, 해당 변형을 피하기 위해서는 추가적인 공간 사용이 필요합니다 |
| 5 | + * |
| 6 | + * Big O |
| 7 | + * - M: 주어진 matrix의 행의 개수 |
| 8 | + * - N: 열의 개수 |
| 9 | + * |
| 10 | + * - Time complexity: O(MN) |
| 11 | + * - Space complexity: O(1) |
| 12 | + */ |
| 13 | + |
| 14 | +class Solution { |
| 15 | +public: |
| 16 | + pair<int, int> rotate(pair<int, int> dir) { |
| 17 | + // 시계방향 90도 회전 |
| 18 | + // 행렬곱으로 구해줄 수 있습니다 |
| 19 | + // | 0 -1 | | dir.first | = | -dir.second | |
| 20 | + // | 1 0 | | dir.second | | dir.first | |
| 21 | + return {dir.second, -dir.first}; |
| 22 | + } |
| 23 | + |
| 24 | + pair<int, int> get_next(pair<int, int> curr, pair<int, int> dir) { |
| 25 | + return {curr.first + dir.first, curr.second + dir.second}; |
| 26 | + } |
| 27 | + |
| 28 | + vector<int> spiralOrder(vector<vector<int>>& matrix) { |
| 29 | + int m = matrix.size(); |
| 30 | + int n = matrix[0].size(); |
| 31 | + int cnt = m * n; |
| 32 | + |
| 33 | + pair<int, int> curr = {0, 0}; |
| 34 | + pair<int, int> curr_dir = {0, 1}; |
| 35 | + |
| 36 | + vector<int> res; |
| 37 | + |
| 38 | + while (cnt) { |
| 39 | + res.push_back(matrix[curr.first][curr.second]); |
| 40 | + |
| 41 | + matrix[curr.first][curr.second] = 101; // constraint 밖의 값 101로 방문 여부를 표시합니다 |
| 42 | + --cnt; |
| 43 | + |
| 44 | + pair<int, int> next = get_next(curr, curr_dir); |
| 45 | + |
| 46 | + if (0 > next.first || next.first >= m |
| 47 | + || 0 > next.second || next.second >= n |
| 48 | + || matrix[next.first][next.second] == 101) { |
| 49 | + curr_dir = rotate(curr_dir); |
| 50 | + curr = get_next(curr, curr_dir); |
| 51 | + } else { |
| 52 | + curr = next; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return res; |
| 57 | + } |
| 58 | +}; |
0 commit comments