【程式解題】ZeroJudge - a015矩陣的翻轉 C解法(詳細解說)

解法推導:

例如說有個矩陣A:(括弧太小就不打了)

1 2 3 

4 5 6

翻轉後會變這樣:

1 4

2 5

3 6

也就是說原本是這樣儲存的:

M[0][0]=1,M[0][1]=2,M[0][2]=3

M[1][0]=4,M[1][1]=5,M[1][2]=6

輸出的順序是:

M[0][0]→

M[1][0]

M[0][1]

M[1][1]

M[0][2]

M[1][2]。

很容易就看的出來,其實就是以下程式碼裡把i、j交換的做法。記得for迴圈條件式也要改。

程式碼:


#include <stdio.h>

#include <stdlib.h>


int main(){

int i,j;//loop

int r,c;//row, column

int M[100][100]={0};//input matrix

while(scanf("%d%d",&r,&c)!=-1){//輸入直到EOF

for(i=0;i<r;++i){

for(j=0;j<c;++j){

scanf("%d ",&M[i][j]);//input

}

}

for(i=0;i<c;++i){

for(j=0;j<r;++j){

printf("%d ",M[j][i]);//output

}

printf("\n");

}

}

    return 0;

}

留言

張貼留言

這個網誌中的熱門文章

【程式解題】2019年4月TOI練習賽新手組 - 滿意度調查 (Survey of Satisfaction) C解法(註解版)

【程式解題】 ZeroJudge a038數字翻轉 C解法(逐行註解)