Wednesday, September 25, 2019

C++: Print a Matrix in Spiral Form

We are given a matrix of any dimension, say 3x3, 4x4 or 4x3, and we are required to print the elements of the matrix in spiral form.


#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 4
void printMatrixSpiral(int m, int n, int mat[R][C]) {
int row = 0, col = 0;
while(row<m && col<n) {
for(int i=col; i<n; i++) {
cout<<mat[row][i]<<" ";
}
row++;
for(int i = row; i<m; i++) {
cout<<mat[i][n-1]<<" ";
}
n--;
if(row<m) {
for(int i=n-1; i>=col; i--){
cout<<mat[m-1][i]<<" ";
}
}
m--;
if(col<n) {
for(int i= m-1; i>=row; i--) {
cout<<mat[i][col]<<" ";
}
}
col++;
}
}
int main() {
int mat[R][C] = {{1, 2, 3, 4},
{5, 6, 7,8},
{9, 10, 11, 12}
};
printMatrixSpiral(R, C, mat);
return 0;
}
Output: 1 2 3 4 8 12 11 10 9 5 6 7

No comments:

Post a Comment