๋์ด๋: Medium
ํค์๋: Array
๋ฌธ์
์ฃผ์ด์ง n x n 2์ฐจ์ ํ๋ ฌ์ ์ด๋ฏธ์ง๋ฅผ ๋ํ๋
๋๋ค. ์ด ์ด๋ฏธ์ง๋ฅผ 90๋(์๊ณ ๋ฐฉํฅ)๋ก ํ์ ํ์ญ์์ค.
์ด๋ฏธ์ง๋ฅผ ์ ์๋ฆฌ์์ (in-place) ํ์ ํด์ผ ํ๋ฏ๋ก ์
๋ ฅ 2์ฐจ์ ํ๋ ฌ์ ์ง์ ์์ ํด์ผ ํฉ๋๋ค.
๋ค๋ฅธ 2์ฐจ์ ํ๋ ฌ์ ํ ๋นํ์ฌ ํ์ ํ์ง ๋ง์ญ์์ค.
๋ฌธ์ ์๋ฌธ : https://leetcode.com/problems/rotate-image/description/
๋ฌธ์ ํ์ด:
์ฐธ๊ณ ๋ก, ์ด๋ฒ ํฌ์คํ
์ผ๋ก ์ ๋ฆฌํ ์ฝ๋๋ ์๋๊ฐ ๋น ๋ฅธ solution์ ์๋๋ค. ๋ค๋ง ๋ฌธ์ ํด๊ฒฐ ๊ณผ์ ๊ณผ ๊ฐ์ด ์ ๋ฆฌํด๋ณด๋ฉด ์ข์ง ์์๊น ์ถ๋ค.
์ผ๋จ ๋ฌธ์ ๋ฅผ ์ดํดํ๋ ๊ณผ์ ๋ถํฐ ์์ํด๋ณด๋ฉด, ๋ฌธ์ ์์ ์ ์ํ ์กฐ๊ฑด์ ๊ฐ๋จํ ์์๋ฅผ ํตํด ์ดํดํ๋ ๊ฒ์ด ํ์ํ๋ค.
๋๋ 3 x 3 ์์ ๋ฅผ ์ฌ์ฉํด์ ๋ฌธ์ ๋ฅผ ๋ถ์ํ๋ค. 90๋ clock-wise๋ก ํ์ ์ํฌ ๋ index์ ์ผ์ด๋๋ ์ผ์ ์ดํดํ๋ ๊ฒ ๋ถํฐ ์์ํด๋ณด๋ฉด ์ข๋ค. ๊ทธ๋ฌ๊ณ ๋์, ๋ณธ ๋ฌธ์ ๊ฐ in-place๋ก ์งํ๋์ด์ผ ํ๋ค๋ ์ ์์ ์ฐฉ์ํด์ rotateํ๋ ์ ๋ค์ ํ๋ฒ์ ์ฐ์์ ์ผ๋ก ์ฒ๋ฆฌํด์ฃผ๋ ๊ฒ ์ข๋ค๋ ์์ด๋์ด๊น์ง ๋์ถํ๋ค.
์ด๋ก๋ถํฐ ๊ท์น์ ์ฐพ์๋ด๊ณ ์ฝ๋๋ก ์ฎ๊ฒจ๋ณด๋ฉด ๋ค์๊ณผ ๊ฐ๋ค.
์ฐธ๊ณ ๋ก, degrees vector๋ ๊ทธ๋ฅ ์๊ณ ๋ฆฌ์ฆ์ ๋ํ readability๋ฅผ ์ํด ์ด๊ฑฐ์ง๋ง ์ฌ์ค์ ๋๋ฏธ ๋ฒกํฐ์ด๋ค.
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
const auto N = matrix.size();
vector<int> degrees = {0, 90, 180, 270};
for(int row = 0; row < round(N / 2.0); ++ row){
for(int col = row; col < N-row-1; ++col){
int target = matrix[row][col];
for(auto degree: degrees){
int tmp = row;
row = col;
col = (N -1) - tmp;
tmp = matrix[row][col];
matrix[row][col] = target;
target = tmp;
}
}
}
}
};
์ฝ๋๊ฐ ์กฐ๊ธ ์ง์ ๋ถํ๋๊น swap ํจ์๋ฅผ ์จ์ ์กฐ๊ธ ๋ ์ฝ๊ธฐ ํธํ๊ฒ ๋ง๋ค์ด๋ณด๋ฉด
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
const auto N = matrix.size();
vector<int> degrees = {0, 90, 180, 270};
for(int row = 0; row < round(N / 2.0); ++ row){
for(int col = row; col < N-row-1; ++col){
int target = matrix[row][col];
for(auto degree: degrees){
swap(row, col);
col = (N-1) - col;
swap(matrix[row][col], target);
}
}
}
}
};
์ข ๋ ๋น ๋ฅด๊ฒ ์ฝ๋๋ฅผ ์ต์ ํํ๋ ค๋ฉด transpose๋ฅผ ๋จผ์ ์ํค๊ณ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ฉด ๋น ๋ฅผ ๊ฒ ๊ฐ๋ค.
๊ธฐ๋ณธ์ ์ผ๋ก transpose๋ฅผ ์ํค๋ ๊ฒ์ row col๋ง ๋ฐ๊พธ๋ฉด ๋๊ธฐ ๋๋ฌธ์ ์ฝ๋ ๋ณต์ก๋๊ฐ ๋์ง ์์ผ๋๊น transpose๋ก ์ ๊ทผํด๋ณด๋ ๊ฒ๋ ์ข๊ฒ ๋ค.