【題解】ZeroJudge b965: 第 2 題 矩陣轉換

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=b965
【解題想法】先實作兩個函式,分別處理「逆翻轉」和「逆旋轉」,會讓主程式比較乾淨直覺。
【Tag】多重迴圈、函數

  • rFlip( ):逆翻轉
  • rRotate( ):逆旋轉
#include <iostream>
using namespace std;
  
int R, C, M, x;
int a[11][11], b[11][11];
  
void rFlip(){
    for (int i=0; i<R; i++){
        for (int j=0; j<C; j++){
            b[i][j] = a[i][j];
        }
    }
    for (int i=0; i<R; i++){
        for (int j=0; j<C; j++){
            a[i][j] = b[R-1-i][j];
        }
    }
}
  
void rRotate(){
    for (int i=0; i<R; i++){
        for (int j=0; j<C; j++){
            b[i][j] = a[i][j];
        }
    }
    for (int j=C-1; j>=0; j--){
        for (int i=0; i<R; i++){
            a[C-1-j][i] = b[i][j];
        }
    }
    swap(R, C);
}
  
int main() {
    while (cin >> R >> C >> M){
        for (int i=0; i<R; i++){
            for (int j=0; j<C; j++){
                cin >> a[i][j];
            }
        }
        int op[M];
        for (int i=0; i<M; i++){
            cin >> op[i];
        }
        //操作的順序也要逆向進行
        for (int i = M - 1; i >= 0; i--) {
            if (op[i] == 0) rRotate();
            else rFlip();
        }
  
        cout << R << ' ' << C << '\n';
        for (int i=0; i<R; i++){
            for (int j=0; j<C; j++){
                cout << a[i][j];
                if (j < C-1) cout << ' ';
            }
            cout << '\n';
        }
    }
    return 0;
}

while True:
    try:
        r, c, m = map(int, input().strip().split())
        templst = []
        for i in range(r):
            templst.append(list(map(int, input().split())))
        lst = list(map(int, input().split()))
        for i in lst[::-1]:
            if i == 1:
                templst.reverse()
            else:    
                anslst = []
                for i in range(c-1, -1, -1):
                    anslst.append([])
                    for j in range(r):
                        anslst[-1].append(templst[j][i])
                c, r = r, c
                templst = anslst
                
        print(r, c)
        for i in range(r):
            for j in range(c):
                print(templst[i][j], end = '')
                if j != c-1:
                    print(' ', end = '')
            if i != r-1:
                print()
        print()
    except:
        break
分享本文 Share with friends