시뮬레이션과 구현/배열 돌리기
배열 돌리기 1
4gats
2023. 7. 12. 15:11
https://www.acmicpc.net/problem/16926
16926번: 배열 돌리기 1
크기가 N×M인 배열이 있을 때, 배열을 돌려보려고 한다. 배열은 다음과 같이 반시계 방향으로 돌려야 한다. 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]
www.acmicpc.net
min(N, M) mod 2 = 0
반복횟수는 min(n,m) / 2 이다!!
시작 지점을
(0,0), (1,1), ... 이렇게 해서 반시계 방향으로 쭉 바꿔주면 되겠네
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
#include <iostream>
#include <cstring>
using namespace std;
int n, m, r;
int arr[304][304];
int tmp[304][304];
bool chk[304][304];
void rotate()
{
int repeat = min(n, m) / 2;
memcpy(&tmp, &arr, sizeof(arr));
for (int start = 0; start < repeat; start++)
{
//start -> 사각형 테두리 시작점
int x = start, y = start;
// 다시 한 번 시작위치를 방문할 때 까지 반복
while (!chk[x][y])
{
chk[x][y] = true;
// 기준은 m - 1 - start, n - 1 - start
// 오른쪽
if (x == start && y != m - 1 - start)
{
arr[x][y] = tmp[x][y + 1];
y++;
}
// 아래
else if (y == m - 1 - start && x != n - 1 - start)
{
arr[x][y] = tmp[x + 1][y];
x++;
}
// 왼쪽
else if (x == n - 1 - start && y != start)
{
arr[x][y] = tmp[x][y - 1];
y--;
}
// 위
else if (y == start && x != start)
{
arr[x][y] = tmp[x - 1][y];
x--;
}
}
}
}
int main()
{
cin >> n >> m >> r;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> arr[i][j];
}
}
while (r--)
{
memset(chk, false, sizeof(chk));
rotate();
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << arr[i][j] << ' ';
}
cout << '\n';
}
return 0;
}
|
cs |
memcpy 쓰는 거 알아두자!
tmp -> 복사본, arr -> 원본
memcpy(&tmp, &arr, sizeof(arr));