def printSpiralOrder(m):
M = len(m)
N = len(m[0])
top = 0
bottom = M - 1
left = 0
right = N - 1
while True:
# print top row
for i in range(left,right+1):
print m[top][i]
top += 1
if top > bottom:
break
# print right row
for i in range(top,bottom+1):
print m[i][right]
right -= 1
if left > right:
break
# print bottom row
for i in range(left, right+1)[::-1]:
print m[bottom][i]
bottom -= 1
if top > bottom:
break
# print left row
for i in range(top, bottom+1)[::-1]:
print m[i][left]
left += 1
if left > right:
break
# test cases
m1 = [
[ 1, 2, 3, 4, 5],
[16,17,18,19, 6],
[15,24,25,20, 7],
[14,23,22,21, 8],
[13,12,11,10, 9]
]
m2 = [
[ 1, 2, 3, 4, 5, 6],
[20,21,22,23,24, 7],
[19,32,33,34,25, 8],
[18,31,36,35,26, 9],
[17,30,29,28,27,10],
[16,15,14,13,12,11]
]
printSpiralOrder(m1)
printSpiralOrder(m2)
#include <stdio.h>
/* declare m as pointer to array 5 of int */
void printSpiralOrder5(int (*m)[5]){
int top = 0;
int bottom = 5 - 1;
int left = 0;
int right = 5 - 1;
while(1){
/* print top row */
for(int i = left; i <= right; i++){
printf("%d\n", m[top][i]);
}
top++;
if(top>bottom){
break;
}
/* print right row */
for(int i = top; i <= bottom; i++){
printf("%d\n", m[i][right]);
}
right--;
if(right<left){
break;
}
/* print bottom row */
for(int i = right; i >= left; i--){
printf("%d\n", m[bottom][i]);
}
bottom--;
if(bottom<top){
break;
}
/* print left row */
for(int i = bottom; i >=top; i--){
printf("%d\n", m[i][left]);
}
left++;
if(left>right){
break;
}
}
}
/* declare m as pointer to array 6 of int */
void printSpiralOrder6(int (*m)[6]){
int top = 0;
int bottom = 6 - 1;
int left = 0;
int right = 6 - 1;
while(1){
/* print top row */
for(int i = left; i <= right; i++){
printf("%d\n", m[top][i]);
}
top++;
if(top>bottom){
break;
}
/* print right row */
for(int i = top; i <= bottom; i++){
printf("%d\n", m[i][right]);
}
right--;
if(right<left){
break;
}
/* print bottom row */
for(int i = right; i >= left; i--){
printf("%d\n", m[bottom][i]);
}
bottom--;
if(bottom<top){
break;
}
/* print left row */
for(int i = bottom; i >=top; i--){
printf("%d\n", m[i][left]);
}
left++;
if(left>right){
break;
}
}
}
int main(){
/* test cases */
int m1[5][5] = {
{ 1, 2, 3, 4, 5},
{16,17,18,19, 6},
{15,24,25,20, 7},
{14,23,22,21, 8},
{13,12,11,10, 9}
};
int m2[6][6] = {
{ 1, 2, 3, 4, 5, 6},
{20,21,22,23,24, 7},
{19,32,33,34,25, 8},
{18,31,36,35,26, 9},
{17,30,29,28,27,10},
{16,15,14,13,12,11}
};
printSpiralOrder5(m1);
printSpiralOrder6(m2);
return 0;
}