#include <stdio.h>
void spiralTraversal(int rows, int cols, int matrix[rows][cols]) {
int top = 0, bottom = rows - 1;
int left = 0, right = cols - 1;
while (top <= bottom && left <= right) {
// Traverse from left to right on top row
for (int i = left; i <= right; i++) {
printf("%d", matrix[top][i]);
if (!(top == bottom && i == right)) printf(" -> ");
}
top++;
// Traverse from top to bottom on right column
for (int i = top; i <= bottom; i++) {
printf("%d", matrix[i][right]);
if (!(i == bottom && left == right)) printf(" -> ");
}
right--;
if (top <= bottom) {
// Traverse from right to left on bottom row
for (int i = right; i >= left; i--) {
printf("%d", matrix[bottom][i]);
if (!(bottom == top && i == left)) printf(" -> ");
}
bottom--;
}
if (left <= right) {
// Traverse from bottom to top on left column
for (int i = bottom; i >= top; i--) {
printf("%d", matrix[i][left]);
if (!(i == top && left == right)) printf(" -> ");
}
left++;
}
}
printf("\n");
}
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
spiralTraversal(3, 3, matrix);
return 0;
}while (top <= bottom && left <= right) {
continue spiral while boundaries are valid
for (int i = left; i <= right; i++) {
traverse top row left to right
move top boundary down after top row traversal
for (int i = top; i <= bottom; i++) {
traverse right column top to bottom
move right boundary left after right column traversal
if (top <= bottom) { for (int i = right; i >= left; i--) {
traverse bottom row right to left if still valid
move bottom boundary up after bottom row traversal
if (left <= right) { for (int i = bottom; i >= top; i--) {
traverse left column bottom to top if still valid
move left boundary right after left column traversal
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5