Skip to content

[Algorithm] 행렬 테두리 회전하기 #107

Description

@hwangJi-dev

💬 문제

https://school.programmers.co.kr/learn/courses/30/lessons/77485


💬 Idea

  1. rows, columns 크기의 행렬을 생성한다

  2. 쿼리를 돌면서 행렬 테두리를 회전시킨다

    [ 행렬 테두리 회전 로직 ]

    • ㅡ : 시작 y 고정 / 시작 x+1 부터 끝 x까지 돌면서 좌표의 이전 좌표값으로 바꿔준다.
    • | : 끝 x 고정 / 시작 y+1 부터 끝 y까지 돌면서 좌표의 이전 좌표값으로 바꿔준다.
    • ㅡ : 끝 y 고정 / 끝 x-1 부터 시작 x까지 돌면서 좌표의 이전 좌표값으로 바꿔준다.
    • | : 시작 x 고정 / 끝 y-1 부터 시작 y까지 돌면서 좌표의 이전 좌표값으로 바꿔준다.
    • 시작좌표값을 처음에 저장한 시작점에 들어가야할 숫자로 바꿔준다.

💬 풀이

varans:[Int]=[]func solution(_ rows:Int, _ columns:Int, _ queries:[[Int]])->[Int]{vararr:[[Int]]=[]
// 행렬 생성
foriin0..<rows {
arr.append([Int]((i * columns)+1...(i * columns)+ columns))}forqueryin queries {
arr =rotateArr(arr,query[1]-1,query[0]-1,query[3]-1,query[2]-1)}return ans
}
/// 행렬 테두리를 회전하는 메서드
func rotateArr(_ arr:[[Int]], _ x1:Int, _ y1:Int, _ x2:Int, _ y2:Int)->[[Int]]{varrotateArr= arr
letfirst=rotateArr[y1 +1][x1] // 시작점에 들어가야할 숫자 저장
varchangeArr=[first]
// - 👈🏻
// | |
// -
foriin x1 +1...x2 {rotateArr[y1][i]=arr[y1][i -1]
changeArr.append(arr[y1][i -1])}
// - // | |👈🏻
// -
foriin y1 +1...y2 {rotateArr[i][x2]=arr[i -1][x2]
changeArr.append(arr[i -1][x2])}
// - // | | // - 👈🏻
foriinstride(from: x2 -1, to: x1 -1, by:-1){rotateArr[y2][i]=arr[y2][i +1]
changeArr.append(arr[y2][i +1])}
// - // |👈🏻 | // -
foriinstride(from: y2 -1, to: y1, by:-1){rotateArr[i][x1]=arr[i +1][x1]
changeArr.append(arr[i +1][x1])}rotateArr[y1][x1]= first // 시작점에 들어가야할 숫자 할당
ans.append(changeArr.sorted().first!) // 이동한 숫자 중 최솟값 구하기
return rotateArr
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions