Skip to content

Commit

Permalink
Merge pull request #478 from obzva/main
Browse files Browse the repository at this point in the history
[Flynn] Week 6 Sprial Matrix Refactor
  • Loading branch information
obzva authored Sep 21, 2024
2 parents 26691e9 + d14eb06 commit cfc0c46
Showing 1 changed file with 68 additions and 1 deletion.
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๋น„ํŠธ ์ •์ˆ˜ ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค
* - ๋” ์ด์ƒ ์ž…๋ ฅ ๋ฐฐ์—ด์„ ๋ณ€ํ˜•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค
* - ๊ณต๊ฐ„๋ณต์žก๋„๊ฐ€ ๊ฐœ์„ ๋˜๊ณ  ์‹ค์ œ ๊ณต๊ฐ„ ์‚ฌ์šฉ๋Ÿ‰๋„ ์ค„์–ด๋“ญ๋‹ˆ๋‹ค
*
* 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;
}
};

0 comments on commit cfc0c46

Please sign in to comment.