1. 程式人生 > >矩陣原地轉置,空間複雜度為O(1)(暫時先儲存下來)

矩陣原地轉置,空間複雜度為O(1)(暫時先儲存下來)

#include<iostream>
using namespace std;
 
/* 後繼 */
int getNext(int i, int m, int n)
{
    return (i%n)*m + i/n;
}
 
/* 前驅 */
int getPre(int i, int m, int n)
{
    return (i%m)*n + i/m;
}
 
/* 處理以下標i為起點的環 */
void movedata(int *mtx, int i, int m, int n)
{
    int temp = mtx[i];  // 暫存
    int cur = i;       // 當前下標
    int pre = getPre(cur, m, n);     while(pre != i)     {         mtx[cur] = mtx[pre];         cur = pre;         pre = getPre(cur, m, n);     }     mtx[cur] = temp; }   /* 轉置,即迴圈處理所有環 */ void transpose(int *mtx, int m, int n) {     for(int i=0; i<m*n; ++i)     {         int next = getNext(i, m, n);         while
(next > i) // 若存在後繼小於i說明重複             next = getNext(next, m, n);         if(next == i)   // 處理當前環             movedata(mtx, i, m, n);     } }   /* 輸出矩陣 */ void print(int *mtx, int m, int n) {     for(int i=0; i<m*n; ++i)     {         if((i+1)%n == 0)             cout << mtx[i] << "\n";         else
            cout << mtx[i] << " ";     } }   /* 測試 */ int main() {     int matrix[4*2] = {1,2,3,4,5,6,7,8};     cout << "Before matrix transposition:" << endl;     print(matrix, 4, 2);     transpose(matrix, 4, 2);     cout << "After matrix transposition:" << endl;     print(matrix, 2, 4);     return 0; }