Programing/백준, 프로그래머스(C++)

[C++][백준 17276] 배열 돌리기

hye3193 2025. 1. 20. 13:08

https://www.acmicpc.net/problem/17276

풀이

직접 배열을 그려 시계/반시계 방향으로 돌아갈 때 어느 위치에 있던 수가 어디로 가는지 체크해서 그대로 구현하였다

 

제출 코드

#include <iostream>
#include <cstring>
using namespace std;

int arr[500][500];
int res[500][500];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int t, n, degree;
    cin >> t;
    while(t--)
    {
        cin >> n >> degree;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                cin >> res[i][j];

        int mid = n / 2;
        if (degree > 0 && degree != 360)
        {
            for (int d = degree; d != 0; d -= 45)
            {
                memcpy(arr, res, sizeof(arr));
                for (int i = 0; i < n; i++)
                {
                    res[i][n - i - 1] = arr[i][mid];
                    res[mid][n - i - 1] = arr[i][n - i - 1];
                    res[i][i] = arr[mid][i];
                    res[i][mid] = arr[i][i];
                }
            }
        }
        else if (degree < 0)
        {
            for (int d = degree; d != 0; d += 45)
            {
                memcpy(arr, res, sizeof(arr));
                for (int i = 0; i < n; i++)
                {
                    res[i][i] = arr[i][mid];
                    res[mid][i] = arr[i][i];
                    res[i][n - i - 1] = arr[mid][n - i - 1];
                    res[i][mid] = arr[i][n - i - 1];
                }
            }
        }

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
                cout << res[i][j] << ' ';
            cout << '\n';
        }
    }
}

memcpy 함수(헤더 파일 cstring)를 사용해 배열을 복사해주었다

이는 memory + copy의 의미로, 메모리를 복사하는 함수이다

memcpy(복사 받을 메모리의 포인터, 복사할 메모리의 포인터, 복사할 데이터의 크기)

2차원 배열을 복사해야 해서 copy 함수를 사용하려면 반복문을 돌아야 할 것 같아 memcpy를 사용했는데, 후에 찾아보니 copy로도 충분히 가능했다(두 함수의 속도는 동일)

 

copy로 배열 복사: copy(복사할 시작 주소, 복사할 끝 주소, 복사 받을 공간의 시작 주소)

따라서 1차원 배열을 복사할 때에는 copy(arr, arr + size, arr_cpy) 이런 식으로 작성하고

2차원 등의 배열을 복사할 때에는 copy(&arr[0][0], &arr[0][0]+size, &arr_cpy[0][0]) 이와 같이 주소값을 넘겨주면 된다

 

벡터 복사시에는 주소값으로 v.begin, v.end 등을 이용하면 된다