fragment-header
fragment-markdown
홈
로그인
로그아웃
내 블로그
설정
로그인
백준 16926 (C++) 배열 돌리기 1
최초 업로드: 2025-04-13 12:47:05
최근 수정 시간: 2025-07-25 09:58:42
게시자: rlatjwls3333
카테고리: 백준
조회수: 8
# [Gold V] 배열 돌리기 1 #### [문제 링크](https://www.acmicpc.net/problem/16926) ## 문제 설명 <p>크기가 N×M인 배열이 있을 때, 배열을 돌려보려고 한다. 배열은 다음과 같이 반시계 방향으로 돌려야 한다.</p> <pre>A[1][1] ← A[1][2] ← A[1][3] ← A[1][4] ← A[1][5] ↓ ↑ A[2][1] A[2][2] ← A[2][3] ← A[2][4] A[2][5] ↓ ↓ ↑ ↑ A[3][1] A[3][2] → A[3][3] → A[3][4] A[3][5] ↓ ↑ A[4][1] → A[4][2] → A[4][3] → A[4][4] → A[4][5]</pre> <p>예를 들어, 아래와 같은 배열을 2번 회전시키면 다음과 같이 변하게 된다.</p> <pre>1 2 3 4 2 3 4 8 3 4 8 6 5 6 7 8 1 7 7 6 2 7 8 2 9 8 7 6 → 5 6 8 2 → 1 7 6 3 5 4 3 2 9 5 4 3 5 9 5 4 <시작> <회전1> <회전2></pre> <p>배열과 정수 R이 주어졌을 때, 배열을 R번 회전시킨 결과를 구해보자.</p> ## 입력 <p>첫째 줄에 배열의 크기 N, M과 수행해야 하는 회전의 수 R이 주어진다.</p> <p>둘째 줄부터 N개의 줄에 배열 A의 원소 A<sub>ij</sub>가 주어진다.</p> ## 출력 <p>입력으로 주어진 배열을 R번 회전시킨 결과를 출력한다.</p> ## 풀이 #### 배열을 r번 돌리면 되는 문제입니다. 배열 안에서 둥글게 r번 돌리는 총 횟수는 min(n, m)/2번입니다. r은 각각 배열 안에서 돌리는 총 개수로 모듈러 연산을 해서 최소화할 수 있습니다. ``` c++ #include<bits/stdc++.h> using namespace std; int n, m, r; int arr[300][300]; void rotate(int depth, int cnt) { cnt %= ((n-depth*2)*2+(m-depth*2-2)*2); while(cnt--) { int tmp = arr[depth][depth]; for(int i=depth+1;i<m-depth;i++) arr[depth][i-1] = arr[depth][i]; for(int i=depth+1;i<n-depth;i++) arr[i-1][m-depth-1] = arr[i][m-depth-1]; for(int i=m-depth-2;i>=depth;i--) arr[n-depth-1][i+1] = arr[n-depth-1][i]; for(int i=n-depth-2;i>=depth;i--) arr[i+1][depth] = arr[i][depth]; arr[depth+1][depth] = tmp; } } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> r; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin >> arr[i][j]; } } for(int i=0;i<min(n, m)/2;i++) { rotate(i, r); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cout << arr[i][j] << ' '; } cout << '\n'; } } ```