코딩테스트

[Swift 알고리즘] LeetCode - 48. Rotate Image

유정주 2022. 7. 31. 12:33
반응형

Github

 

GitHub - jeongju9216/SwiftAlgorithm: 스위프트 알고리즘

스위프트 알고리즘. Contribute to jeongju9216/SwiftAlgorithm development by creating an account on GitHub.

github.com

 

문제 링크

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

 

Rotate Image - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

풀이

이번 문제는 행렬을 90도 회전하는 문제인데요. 

새로운 2차원 배열을 만들지 않고 해결해야 합니다.

 

새로운 배열을 만들지 말라고 해서 뇌정지가 왔는데

손으로 그려가며 생각하니 교체되는 index 사이에 규칙이 있다는 것을 발견했습니다.

 

1. 모든 행(row)을 reverse 합니다.

행이 1, 2, 3 이라면 3, 2, 1로 뒤집습니다.

 

2. 규칙에 따라 원소를 swap 합니다.

matrix가 3 x 3 이라면,

(0, 0) <-> (2, 2)

(0, 1) <-> (1, 2)

(0, 2) <-> (0, 2)

 

(1, 0) <-> (2, 1)

(1, 1) <-> (1, 1)

 

(2,0) <-> (2,0)

으로 swap 합니다.

이를 코드로 표현하면 "matrix[i][n-j-1] <-> matrix[j][n-i-1]"가 됩니다.

 

+)

새로운 배열을 만들지 말라는 조건이 까다로웠지만

나름대로 재밌었던 문제였습니다.

 

전체 코드

더보기
class Solution {
    func rotate(_ matrix: inout [[Int]]) {
        let len = matrix.count

        for i in 0..<len {
            matrix[i] = matrix[i].reversed()
        }
        
        for i in 0..<len {
            for j in i..<len {
                let temp = matrix[i][len-j-1]
                matrix[i][len-j-1] = matrix[j][len-i-1]
                matrix[j][len-i-1] = temp
            }
        }
    }
}

아직은 초보 개발자입니다.

더 효율적인 코드 훈수 환영합니다!

공감 댓글 부탁드립니다.

 

 

반응형