@@ -56,3 +56,70 @@ class Solution {
56
56
return res;
57
57
}
58
58
};
59
+
60
+ /* *
61
+ * 풀이
62
+ * - 위와 동일하지만, 방문 여부를 기록하기 위해 m * n 크기의 정수형 2차원 배열 대신
63
+ * m 크기의 16비트 정수 배열을 사용합니다
64
+ * - 더 이상 입력 배열을 변형하지 않습니다
65
+ * - 공간복잡도가 개선되고 실제 공간 사용량도 줄어듭니다
66
+ *
67
+ * Big O
68
+ * - M: 주어진 matrix의 행의 개수
69
+ * - N: 열의 개수
70
+ *
71
+ * - Time complexity: O(MN)
72
+ * - Space complexity: O(M)
73
+ */
74
+
75
+ class Solution {
76
+ public:
77
+ pair<int , int > rotate (pair<int , int > dir) {
78
+ return {dir.second , -dir.first };
79
+ }
80
+
81
+ pair<int , int > get_next (pair<int , int > curr, pair<int , int > dir) {
82
+ return {curr.first + dir.first , curr.second + dir.second };
83
+ }
84
+
85
+ void mark_visited (vector<uint16_t >& visit, pair<int , int > curr) {
86
+ visit[curr.first ] |= 1 << curr.second ;
87
+ }
88
+
89
+ bool is_visited (vector<uint16_t > const visit, pair<int , int > curr) {
90
+ return visit[curr.first ] & 1 << curr.second ;
91
+ }
92
+
93
+ vector<int > spiralOrder (vector<vector<int >>& matrix) {
94
+ int m = matrix.size ();
95
+ int n = matrix[0 ].size ();
96
+ int cnt = m * n;
97
+
98
+ pair<int , int > curr = {0 , 0 };
99
+ pair<int , int > curr_dir = {0 , 1 };
100
+
101
+ vector<uint16_t > visit (m, 0 );
102
+
103
+ vector<int > res;
104
+
105
+ while (cnt) {
106
+ res.push_back (matrix[curr.first ][curr.second ]);
107
+
108
+ mark_visited (visit, curr);
109
+ --cnt;
110
+
111
+ pair<int , int > next = get_next (curr, curr_dir);
112
+
113
+ if (0 > next.first || next.first >= m
114
+ || 0 > next.second || next.second >= n
115
+ || is_visited (visit, next)) {
116
+ curr_dir = rotate (curr_dir);
117
+ curr = get_next (curr, curr_dir);
118
+ } else {
119
+ curr = next;
120
+ }
121
+ }
122
+
123
+ return res;
124
+ }
125
+ };
0 commit comments