Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Flynn] Week 6 Sprial Matrix Refactor #478

Merged
merged 2 commits into from
Sep 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 68 additions & 1 deletion spiral-matrix/flynn.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* - N: 열의 개수
*
* - Time complexity: O(MN)
* - Space complexity: O(1)
* - Space complexity: O(MN)
*/

class Solution {
Expand Down Expand Up @@ -56,3 +56,70 @@ class Solution {
return res;
}
};

/**
* 풀이
* - 위와 동일하지만, 방문 여부를 기록하기 위해 m * n 크기의 정수형 2차원 배열 대신
* m 크기의 16비트 정수 배열을 사용합니다
* - 더 이상 입력 배열을 변형하지 않습니다
* - 공간복잡도가 개선되고 실제 공간 사용량도 줄어듭니다
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와 여기서 비트연산자라니.. 감탄하고 갑니다 ㅋㅋ
1 <= m, n <= 10 라는 조건을 잘 캐치하셨네요. 항상 문제 조건을 정말 잘 파악해서 푸시는것같습니다!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

비트 연산은 생각지 못했는데... 잘 배웠습니다!

*
* Big O
* - M: 주어진 matrix의 행의 개수
* - N: 열의 개수
*
* - Time complexity: O(MN)
* - Space complexity: O(M)
*/

class Solution {
public:
pair<int, int> rotate(pair<int, int> dir) {
return {dir.second, -dir.first};
}

pair<int, int> get_next(pair<int, int> curr, pair<int, int> dir) {
return {curr.first + dir.first, curr.second + dir.second};
}

void mark_visited(vector<uint16_t>& visit, pair<int, int> curr) {
visit[curr.first] |= 1 << curr.second;
}

bool is_visited(vector<uint16_t> const visit, pair<int, int> curr) {
return visit[curr.first] & 1 << curr.second;
}

vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int cnt = m * n;

pair<int, int> curr = {0, 0};
pair<int, int> curr_dir = {0, 1};

vector<uint16_t> visit(m, 0);

vector<int> res;

while (cnt) {
res.push_back(matrix[curr.first][curr.second]);

mark_visited(visit, curr);
--cnt;

pair<int, int> next = get_next(curr, curr_dir);

if (0 > next.first || next.first >= m
|| 0 > next.second || next.second >= n
|| is_visited(visit, next)) {
curr_dir = rotate(curr_dir);
curr = get_next(curr, curr_dir);
} else {
curr = next;
}
}

return res;
}
};