Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Archives
Today
Total
관리 메뉴

Life Engineering

[프로그래머스] 행렬 테두리 회전하기 (C++) 본문

Problem Solving

[프로그래머스] 행렬 테두리 회전하기 (C++)

흑개 2021. 9. 30. 21:22

 

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

 

코딩테스트 연습 - 행렬 테두리 회전하기

6 6 [[2,2,5,4],[3,3,6,6],[5,1,6,3]] [8, 10, 25] 3 3 [[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]] [1, 1, 5, 3]

programmers.co.kr

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int matrix[101][101];

int move(int x1, int y1, int x2, int y2){
    int x=x1;
    int y=y1;
    int temp=matrix[x1+1][y1];
    int val;
    vector<int> v;
    while (y<=y2){
        val=matrix[x][y];
        matrix[x][y]=temp;
        v.push_back(matrix[x][y]);
        temp=val;
        y++;
    }
    x=x1+1; y=y2;
    while (x<=x2){
        val=matrix[x][y];
        matrix[x][y]=temp;
        v.push_back(matrix[x][y]);
        temp=val;
        x++;
    }
    x=x2; y=y2-1;
    while (y>=y1){
        val=matrix[x][y];
        matrix[x][y]=temp;
        v.push_back(matrix[x][y]);
        temp=val;
        y--;
    }
    x=x2-1; y=y1;
    while (x>x1){
        val=matrix[x][y];
        matrix[x][y]=temp;
        v.push_back(matrix[x][y]);
        temp=val;
        x--;
    }
    return *min_element(v.begin(), v.end());
}

vector<int> solution(int rows, int columns, vector<vector<int>> queries) {
    vector<int> answer;
    int x=1;
    for (int i=1; i<=rows; i++){
        for (int j=1; j<=columns; j++){
            matrix[i][j]=x;
            x++;
        }
    }
    for (int i=0; i<queries.size(); i++){
        int x1=queries[i][0];
        int y1=queries[i][1];
        int x2=queries[i][2];
        int y2=queries[i][3];
        answer.push_back(move(x1,y1,x2,y2));
    }
    return answer;
}

행렬 테두리 부분을 시계방향으로 회전시키는 문제.

빡구현 문제이다.

 

시계방향으로 x,y 좌표를 움직이면서 자기 값 저장하고, temp에 저장해놓은 자기 앞 값을 자기 값으로 갱신한다..이 과정을 반복하면 된다.

 

 

다른 분들 코드를 보니, 

위에서는(그러니까 행(x)만 ++ 움직이는 경우) 자기 아래쪽 값을 갖다 쓰면 변수에 따로 자기 값을 저장할 필요 없이 바로 갱신해주면 된다.

오른쪽에서는(열(y)만 움직이는 경우 자기 왼쪽값을 갖다 쓰면된다.

움직이는 방향을 거꾸로 설정해주면 값 따로 저장해 줄 필요 없다. (시계방향으로 움직일 때 위쪽으로 움직인다면 아래쪽으로 for문 향하게 한다든지) 

이런식으로 방법을 조금 바꿔주면 더 코드가 짧아질 수 있다.