본문 바로가기

알고리즘/기본 문법

<알고리즘> 2차원 배열 회전

 

 

 

 

 

코드


#include<bits/stdc++.h>
using namespace std;

void Print(vector<vector<int>>& v)
{
	for(vector<int> i : v)
	{
		for(int j : i)
		{
			cout << j << " ";
		}
		cout << "\n";
	}
	cout << "\n";
}

// 왼쪽으로 90도 회전
void rotateLeft90(vector<vector<int>> &key)
{
	int m = key.size();
	vector<vector<int>> temp(m, vector<int>(m, 0));
	for(int i = 0; i < m; i++)
	{
		for(int j = 0; j < m; j++)
			temp[i][j] = key[j][m - i - 1];
	}
	key = temp;
	return;	
}

// 오른쪽으로 90도 회전
void rotateRight90(vector<vector<int>> &key)
{
	int m = key.size();
	vector<vector<int>> temp(m, vector<int>(m, 0));
	for(int i = 0; i < m; i++)
	{
		for(int j = 0; j < m; j++)
			temp[i][j] = key[m - j - 1][i];
	}
	key = temp;
	return;	
}

	
int main()
{
	vector<vector<int>> val = {
	{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}
	};
	
	Print(val);
	
	cout << "Left 90 Rotate" << "\n";
	cout << "\n";
	rotateLeft90(val);
	Print(val);
	
	
	cout << "Right 90 Rotate" << "\n";
	cout << "\n";
	rotateRight90(val);
	rotateRight90(val);
	Print(val);
	
	
	return 0;
}

/*
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

Left 90 Rotate

5 10 15 20 25
4 9 14 19 24
3 8 13 18 23
2 7 12 17 22
1 6 11 16 21

Right 90 Rotate

21 16 11 6 1
22 17 12 7 2
23 18 13 8 3
24 19 14 9 4
25 20 15 10 5
*/
 

'알고리즘 > 기본 문법' 카테고리의 다른 글

DFS 코드 구현 2가지 방법  (0) 2022.08.09
DFS, BFS  (0) 2022.08.02
<알고리즘> 입출력 싱크  (0) 2022.04.22
<알고리즘> 2차원 배열 수정하는 함수  (0) 2022.04.22
<알고리즘> n진법 변환  (0) 2022.04.22