오늘의 알고리즘

[C++]2021 Dev-Matching: 웹 백엔드 개발자(상반기)행렬 테두리 회전하기(프로그래머스 2레벨)

하늘하늘 . 2022. 2. 11. 16:41
#include <string>
#include <vector>
 
using namespace std;
 
vector<int> solution(int rows, int columns, vector<vector<int>> queries)
{
    vector<int> answer;
    vector<vector<int>> vecInt;
    vecInt.resize(rows);
 
    int iPreviousTemp = -1;
    int iNextTemp = -1;
    int iSmall = -1;
 
    int iFirstRow = -1;
    int iFirstCol = -1;
    int iLastRow = -1;
    int iLastCol = -1;
 
    for (int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < columns; ++j)
        {
            vecInt[i].push_back(i * columns + j + 1);
        }
    }
 
    for (int i = 0; i < queries.size(); ++i)
    {
        //      →  (1)
        // (4)↑  ↓(2)
        //      ←  (3)
        iFirstRow = queries[i][0] - 1;  // 첫번째 횡
        iFirstCol = queries[i][1] - 1;  // 첫번째 열
        iLastRow = queries[i][2] - 1;   // 마지막 횡
        iLastCol = queries[i][3] - 1;   // 마지막 열
 
        // 1. 넣기 전에 본인을 다음 Temp에 넣는다
        // 2. 이전 Temp에 본인을 넣는다
        // 3. 이전 Temp를 다음 Temp로 변경한다.
        iPreviousTemp = vecInt[iFirstRow + 1][iFirstCol];
        iSmall = iPreviousTemp;
 
        // 1. 첫번재 횡 고정
        for (int j = iFirstCol; j < iLastCol; ++j)
        {
            if (iSmall > vecInt[iFirstRow][j])
                iSmall = vecInt[iFirstRow][j];
 
            iNextTemp = vecInt[iFirstRow][j];
            vecInt[iFirstRow][j] = iPreviousTemp;
            iPreviousTemp = iNextTemp;
        }
 
        // 2. 마지막 열 고정
        for (int j = iFirstRow; j < iLastRow; ++j)
        {
            if (iSmall > vecInt[j][iLastCol])
                iSmall = vecInt[j][iLastCol];
 
            iNextTemp = vecInt[j][iLastCol];
            vecInt[j][iLastCol] = iPreviousTemp;
            iPreviousTemp = iNextTemp;
        }
 
        // 3. 마지막 횡 고정
        for (int j = iLastCol; j > iFirstCol; --j)
        {
            if (iSmall > vecInt[iLastRow][j])
                iSmall = vecInt[iLastRow][j];
 
            iNextTemp = vecInt[iLastRow][j];
            vecInt[iLastRow][j] = iPreviousTemp;
            iPreviousTemp = iNextTemp;
        }
 
        // 4. 첫번째 열 고정
        for (int j = iLastRow; j > iFirstRow; --j)
        {
            if (iSmall > vecInt[j][iFirstCol])
                iSmall = vecInt[j][iFirstCol];
 
            iNextTemp = vecInt[j][iFirstCol];
            vecInt[j][iFirstCol] = iPreviousTemp;
            iPreviousTemp = iNextTemp;
        }
 
        answer.push_back(iSmall);
        iNextTemp = -1;
        iPreviousTemp = -1;
        iSmall = -1;
    }
 
    return answer;
}

횡 열 체크하기가 제일 까다로웠다.

아예 인트에다가 넣어놓으니까 그~~~ 나마 볼만해져서 정신 잡고 할 수 있었다.