Algolithm-Leetcode/Math & Geometry
Rotate Image
꿀잠마스터
2026. 8. 7. 18:26
https://leetcode.com/problems/rotate-image/description/
Rotate Image - LeetCode
Can you solve this real interview question? Rotate Image - You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place [https://en.wikipedia.org/wiki/In-place_algorithm], which m
leetcode.com
매개변수로 주어진 matrix를 90도 돌리는 문제이다. 이 때 별도의 2차원 배열을 사용하는 것이 아니라. 바로 주어진 matrix 배열을 변화시켜야 한다. void 속성의 메서드로 내부적으로 결과를 해결하는 것 같다.
별도의 배열을 사용할 수 없어서 처음에는 당황했으나 위에서 부터 한 row 씩 돌린다고 생각하며
해결했다. 2차원 배열은 일종의 사각형 형태이므로 상우하좌 순으로 돌아간다는 것을 생각하여
돌려주었다. 이때 각 4개의 방향을 임시 변수로 설정해주었다. 문제를 해결하고 나서 생각하니 temp 를 하나만 사용해도 될 수 있다는 것을 깨달았으나.
블로그에 올리기 위해서는 아래의 초기 코드가 이해를 쉽게 할 수 있다고 생각하여
최초에 풀었던 방식으로 코드를 가져왔다.
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length - 1;
for(int i = 0; i <= n; i++){
// 4분면을 한번에 돌리므로 i row를 돌렸다는 것은 i, n-i 의 row와 col 을 해결한 것이므로
// j = i, j < n -i 조건으로 반복 처리하지 않게한다.
for(int j = i; j < n - i ; j++){
int temp1 = matrix[i][j]; // 상
int temp2 = matrix[j][n - i]; // 우
int temp3 = matrix[n - i][n - j];// 하
int temp4 = matrix[n - j][i]; // 좌
// 회전
matrix[i][j] = temp4;
matrix[j][n - i] = temp1;
matrix[n - i][n - j] = temp2;
matrix[n - j][i] = temp3;
}
}
}
}