Spiral traversal of matrix in c
C program for Spiral traversal of matrix. Here more information.
/*
C Program for
Spiral form of matrix
*/
#include <stdio.h>
#define ROW 7
#define COL 6
void spiral(int data[ROW][COL], int s_row,
int s_col, int e_row,
int e_col, int element) {
// Left to right
for (int i = s_col; i <= e_col && element > 0; ++i) {
element--;
printf(" %3d", data[s_row][i]);
}
// Top to down
for (int i = s_row + 1; i <= e_row && element > 0; ++i) {
element--;
printf(" %3d", data[i][e_col]);
}
// Bottom right to bottom-left
for (int i = e_col - 1; i >= s_col && element > 0; --i) {
element--;
printf(" %3d", data[e_row][i]);
}
// Bottom left to top
for (int i = e_row - 1; i > s_row && element > 0; --i) {
element--;
printf(" %3d", data[i][s_row]);
}
if (s_row + 1 <= e_row - 1 && element > 0) {
// Recursive call
spiral(data, s_row + 1,
s_col + 1,
e_row - 1,
e_col - 1,
element);
}
}
int main() {
int arr[ROW][COL] = {
{1 , 2 , 3 , 4 , 5 , 6} ,
{22 , 23 , 24 , 25 , 26 , 7} ,
{21 , 36 , 37 , 38 , 27 , 8} ,
{20 , 35 , 42 , 39 , 28 , 9} ,
{19 , 34 , 41 , 40 , 29 , 10} ,
{18 , 33 , 32 , 31 , 30 , 11} ,
{17 , 16 , 15 , 14 , 13 , 12}
};
int element = COL * (ROW);
spiral(arr, 0, 0, ROW - 1, COL - 1, element);
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment