Piyush Banerjee
BAN USER#include<iostream>
#define RIGHT 0
#define DOWN 1
#define LEFT 2
#define UP 3
using namespace std;
char arr[5][5] = { 'i', 'l', 'o', 'v', 'e',
'd', 'i', 'n', 't', 'e',
'n', 'e', 'w', 'e', 'p',
'a', 'i', 'v', 'r', 'i',
'm', 'a', 'x', 'e', 'c',
};
int bd_left,bd_top,bd_right,bd_bottom,bd_size=5;
int main(int argc,char* argcv[]) {
int i,j,direction=RIGHT;
bool done=false;
bd_left=bd_top=0;
bd_right=bd_bottom=bd_size-1;
i=bd_top;
j=bd_left;
while(!done) {
cout<<arr[i][j];
switch(direction) {
case RIGHT:
right: j++;
if(j==bd_right+1) {
j--;
direction=DOWN;
goto down;
}
break;
case DOWN:
down: i++;
if(i==bd_bottom+1) {
i--;
direction=LEFT;
goto left;
}
break;
case LEFT:
left: j--;
if(j==bd_left-1) {
j++;
direction=UP;
goto up;
}
break;
case UP:
up: i--;
if(i==bd_top) {
direction=RIGHT;
bd_left++;
bd_top++;
bd_right--;
bd_bottom--;
i=bd_top;
j=bd_left-1;
if(bd_size%2==0 &&
((bd_right-bd_left) == -1) ||
((bd_bottom-bd_top) == -1) ) {
done=true;
}
else if (bd_size%2!=0 &&
((bd_right-bd_left) == 0) ||
((bd_bottom-bd_top) == 0) ) {
cout<<arr[i][++j];
done=true;
break;
}
goto right;
}
}
}
cout<<endl;
return 0;
}
/*
Output :-
iloveepicexamandinterview
*/
This program works perfectly for all square matrices. Just change the matrix and update the bd_size variable appropriately.
- Piyush Banerjee May 20, 2013