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.
Output: 1 2 3 4 8 12 11 10 9 5 6 7
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 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; | |
} |
No comments:
Post a Comment