본문 바로가기
Algorithm/문제풀이_프로그래머스

[Swift][프로그래머스][완전탐색] 행렬 테두리 회전하기

by Joahnee 2022. 4. 25.

요구능력

완전탐색

 

문제풀이

테두리만 회전시키면서 가장 작은값을 result에 저장해두고 회전을 마치면 answer에 하나씩 저장하였다.

 

후기

그냥 구현문제

 

코드

func solution(_ rows:Int, _ columns:Int, _ queries:[[Int]]) -> [Int] {
    var arr = [[Int]]()
    var count = 1
    var answer = [Int]()
    for i in 0..<rows{
        arr.append([])
        for _ in 0..<columns{
            arr[i].append(count)
            count += 1
        }
    }
    for i in queries{
        let startX = i[0] - 1
        let startY = i[1] - 1
        let endX = i[2] - 1
        let endY = i[3] - 1
        
        var curX = startX
        var curY = startY
        var beforeTemp = arr[startX][startY]
        
        var result = Int.max
        for j in stride(from: startY+1, through: endY, by: 1){
            result = min(result, beforeTemp)
            let temp = arr[curX][j]
            arr[curX][j] = beforeTemp
            beforeTemp = temp
            curY = j
        }
        for j in stride(from: startX + 1, through: endX, by: 1){
            result = min(result, beforeTemp)
            let temp = arr[j][curY]
            arr[j][curY] = beforeTemp
            beforeTemp = temp
            curX = j
        }
        for j in stride(from: endY-1, through: startY, by: -1){
            result = min(result, beforeTemp)
            let temp = arr[curX][j]
            arr[curX][j] = beforeTemp
            beforeTemp = temp
            curY = j
        }
        for j in stride(from: endX - 1, through: startX, by: -1){
            result = min(result, beforeTemp)
            let temp = arr[j][curY]
            arr[j][curY] = beforeTemp
            beforeTemp = temp
            curX = j
        }
        answer.append(result)
    }
    
    return answer
}

댓글