1️⃣ 문제
2️⃣ 풀이 방법 및 코드
회전을 할 때, 겹치는 부분이 생기므로 숫자퍼즐 원리처럼 좌측 상단 값을 보류해놓고(temp에 저장), 회전시킨다.
시계 방향으로 회전해야 하니 왼쪽(left) 값들을 올리고, 아래쪽(bottom) 값들을 왼쪽으로 이동해주고, 오른쪽(right) 값들을 내리고, 맨 윗 값들은 오른쪽으로 이동해주었다. 회전과 동시에 min 값도 함께 탐색.
마지막으로 temp에 있던 값을 오른쪽으로 한 칸 이동한 위치에 저장해주고, min 값을 리턴해준다.
소스 코드
import Foundation
var matrix = [[Int]]()
var answer = [Int]()
func solution(_ rows:Int, _ columns:Int, _ queries:[[Int]]) -> [Int] {
for r in 0..<rows {
matrix.append(Array(1 + r*columns...columns + r*columns))
}
queries.forEach {
let (top, left, bottom, right) = ($0[0] - 1, $0[1] - 1, $0[2] - 1, $0[3] - 1)
let temp = matrix[top][left]
var min = temp
for r in top..<bottom {
matrix[r][left] = matrix[r + 1][left]
min = min > matrix[r][left] ? matrix[r][left]: min
}
for c in left..<right {
matrix[bottom][c] = matrix[bottom][c + 1]
min = min > matrix[bottom][c] ? matrix[bottom][c]: min
}
for r in (top+1...bottom).reversed() {
matrix[r][right] = matrix[r - 1][right]
min = min > matrix[r][right] ? matrix[r][right]: min
}
for c in (left+1...right).reversed() {
matrix[top][c] = matrix[top][c - 1]
min = min > matrix[top][c] ? matrix[top][c]: min
}
matrix[top][left + 1] = temp
answer.append(min)
}
return answer
}