-
matrix_Leetcode_48. Rotate Image [swift]알고리즘/알고리즘 문제풀이 2025. 2. 19. 16:55
https://leetcode.com/problems/rotate-image/description/?envType=study-plan-v2&envId=top-100-liked
풀면서 이게 진짜 맞는 방법일까 의심을 정말 많이 한 문제
문제접근
특정 축 기준으로 대칭하는 방법이 있을것같은데,,,
- in-place 알고리즘 이라는 단서가 존재, 문제 내에서도 matrix의 새로운 instance의 생성을 금함.
- 내부 변수를 교환해야하지만, swap할 경우 너무 복잡하므로, 변수하나를 선언하여 해당 공간에 일시 저장
- 일시 저장한 데이터를 matrix의 적합한 좌표에 기입하고, 기입될 위치에 있던 값을 다시 일시저장
정답코드
더보기더보기class Solution { func rotate(_ matrix: inout [[Int]]) { let rotateItteration = matrix.count / 2 let endIndex = matrix.count-1 for itteration in 0..<rotateItteration { var saving = 0 // var target = (0,0) for column in 0..<endIndex - itteration * 2 { for move in 0...3 { switch move { case 0: saving = matrix[itteration + column][endIndex - itteration] matrix[itteration + column][endIndex - itteration] = matrix[itteration][itteration + column] // target = (itteration + column,endIndex - itteration) case 1: let temp = matrix[endIndex - itteration][endIndex - itteration - column] matrix[endIndex - itteration][endIndex - itteration - column] = saving saving = temp // target = (endIndex - itteration, endIndex - itteration - column) case 2: let temp = matrix[endIndex - column - itteration][itteration] matrix[endIndex - column - itteration][itteration] = saving saving = temp // target = (endIndex - column - itteration, itteration) case 3: matrix[itteration][itteration + column] = saving // target = (itteration, itteration + column) default: break } // print(matrix,itteration,column,move, saving, target) } } } } }
다른방법
역시나,, 내가 한 방법은 너무 별로였다.
훨씬 좋은 방법이 있을거라고 생각했다.
처음에 대칭 축을 찾아서 대칭이동 하는 방법이 있을 것 같았는데 역시나,,,
1. y=-x 대칭이동
2. y=0 대칭이동
하면 90도 이동이므로 아래 코드가 된다.
'알고리즘 > 알고리즘 문제풀이' 카테고리의 다른 글
BST_Leetcode_98. Validate Binary Search Tree [swift] (0) 2025.02.19 dijkstra_Leetcode_743. Network Delay Time [swift] (0) 2025.02.19 BinaryTree_Leetcode_543. Diameter of Binary Tree [swift] (0) 2025.02.18 BinaryTree_Leetcode_226. Invert Binary Tree [swift] (0) 2025.02.18 BinaryTree_Leetcode_108. Convert Sorted Array to Binary Search Tree [swift] (0) 2025.02.18