Rotate Image

Edit

Difficulty: MEDIUM

Categories: λ°°μ—΄/λ¬Έμžμ—΄

Source: https://leetcode.com/problems/rotate-image/


Solutions

Add Solution
JAVA 2026-10-04 12:00 Edit
class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        for (int i = 0; i < n; i++) {
            int left = 0, right = n - 1;
            while (left < right) {
                int temp = matrix[i][left];
                matrix[i][left] = matrix[i][right];
                matrix[i][right] = temp;
                left++;
                right--;
            }
        }
    }
}
Notes:

[μžλ™ 풀이 Β· gpt-4.1-mini] n x n 행렬을 μ‹œκ³„λ°©ν–₯으둜 90도 νšŒμ „ν•˜λ €λ©΄, λ¨Όμ € 행렬을 μ „μΉ˜(transpose)ν•œ ν›„ 각 행을 λ’€μ§‘μœΌλ©΄ λœλ‹€. μ „μΉ˜λŠ” ν–‰κ³Ό 열을 λ°”κΎΈλŠ” μž‘μ—…μ΄κ³ , λ’€μ§‘κΈ°λŠ” 각 ν–‰μ˜ μ›μ†Œ μˆœμ„œλ₯Ό λ°˜λŒ€λ‘œ ν•˜λŠ” μž‘μ—…μ΄λ‹€. μ‹œκ°„ O(n^2) Β· 곡간 O(1) 주의: μ „μΉ˜ μ‹œ i와 j λ²”μœ„λ₯Ό 잘λͺ» μ„€μ •ν•˜κ±°λ‚˜, ν–‰ λ’€μ§‘κΈ° μ‹œ 인덱슀 κ΅ν™˜μ„ μ‹€μˆ˜ν•˜κΈ° 쉽닀.