行列の回転の方法
概要
np.rot90(np.rot90(np.rot90(a)))
のように行列を回転させる操作- 行列の回転や転置はアルゴリズムがすでにある
具体例
python
import copy
def print_list(lst):
for ilst in lst:
print(*ilst)
print()
A = [[1, 2, 3], [4,5,6], [7,8,9]]
print_list(A)
"""
1 2 3
4 5 6
7 8 9
"""
## 転置(1, python風)
print("python風")
print_list(list(zip(*A[::-1])))
"""
python風
7 4 1
8 5 2
9 6 3
"""
## 転置(2, most direct)
T = copy.deepcopy(A)
N = len(T)
for i in range(N//2):
for j in range(N-N//2):
T[i][j], T[~j][i], T[~i][~j], T[j][~i] = T[~j][i], T[~i][~j], T[j][~i], T[i][j]
print("most direct")
print_list(T)
"""
most direct
7 4 1
8 5 2
9 6 3
"""
## 転置(3, flip flop)
T = copy.deepcopy(A)
N = len(T)
T.reverse()
for i in range(N):
for j in range(i):
T[i][j], T[j][i] = T[j][i], T[i][j]
print("flip flop")
print_list(T)
"""
flip flop
7 4 1
8 5 2
9 6 3
"""
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void print(vector<vector<int>> m) {
for (auto &sub : m) {
for (auto v : sub) {
cout << v << " ";
}
cout << endl;
}
cout << endl;
}
int main() {
vector<vector<int>> S = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
cout << "default" << endl;
print(S);
reverse(S.begin(), S.end());
for (int i = 0; i < S.size(); i++) {
for (int j = 0; j < i; j++) {
swap(S[i][j], S[j][i]);
}
}
cout << "flip flop" << endl;
print(S);
return 0;
}