Life Engineering
[프로그래머스] 행렬 테두리 회전하기 (C++) 본문
https://programmers.co.kr/learn/courses/30/lessons/77485
#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문 향하게 한다든지)
이런식으로 방법을 조금 바꿔주면 더 코드가 짧아질 수 있다.
'Problem Solving' 카테고리의 다른 글
[BOJ 14503] 로봇 청소기 (C++) (0) | 2021.10.01 |
---|---|
[프로그래머스] 괄호 변환 (C++) (0) | 2021.09.30 |
[프로그래머스] 짝 지어 제거하기 (C++) (0) | 2021.09.30 |
[프로그래머스] 가장 먼 노드 (C++) (0) | 2021.09.27 |
[프로그래머스] 디스크 컨트롤 (C++) (0) | 2021.09.24 |