We are given a matrix of any dimension and we need to turn it by 180 degree. Here is the source code for the algorithm in c++.
Output: 12 11 10 9
8 7 6 5
4 3 2 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
#define R 3 | |
#define C 4 | |
void printMatrix(int mat[][S]); | |
void turnOneEighty(int mat[R][C]) { | |
int row = 0, m = R-1; | |
while(row < m) { | |
for(int i=0; i < C; i++) | |
swap(mat[row][i], mat[m][C-1-i]); | |
row++; | |
m--; | |
if(row == m) { | |
int col = 0, n = C-1; | |
while(col < n) | |
swap(mat[row][col++], mat[row][n--]); | |
} | |
} | |
cout<<"\n\nMatrix turned 180 degree "<<endl; | |
printMatrix(mat); | |
} | |
int main() { | |
int mat[R][C] = { {1, 2, 3, 4}, | |
{5, 6, 7, 8}, | |
{9, 10, 11, 12} }; | |
cout<<"\nOriginal matrix is "<<endl; | |
printMatrix(mat); | |
turnOneEighty(mat); | |
return 0; | |
} |
8 7 6 5
4 3 2 1
No comments:
Post a Comment