Interview Questions

Print a 2D array spirally.

Microsoft Interview Questions and Answers


(Continued from previous question...)

135. Print a 2D array spirally.

Question:
Print a 2D array spirally.


maybe an answer:


int a[3][3] = { {1,2,3},
{4,5,6},
{7,8,9}
};
int m=3, n=3;
for(int i=0; i< m; i++)
{
if(i%2)
for(int j=n-1; j>=0; j--)
cout << a[i][j] << " ";
else
for(int j=0; j<n; j++)
cout << a[i][j] << " ";
cout << endl;
}



maybe an answer2:


input: int[][] arr
output: print output
assumption: Array is not empty

void PrintArray(int[][] arr){
int m = arr[0].Length;
int n = arr.Length;
for (int i=0;i<m;i++) print(arr[0][i]);
int i = 1, step = n-i, x = m-1, y = 0;
Direction dir = Direction.Down;
while(step > 0){
switch(dir){
case Direction.Down:
while(step -- > 0) print(arr[x][++y]);
step = m-i; dir = Direction.Left;
break;
case Direction.Left:
while(step -- > 0) print(arr[--x][y]);
step = m-(++i); dir = Direction.Up;
break;
case Direction.Up:
while(step -- > 0) print(arr[x][--y]);
step = m-i; dir = Direction.Right;
break;
case Direction.Right:
while(step -- > 0) print(arr[++x][y]);
step = m-(++i); dir = Direction.Left;
break;
}
}
}

enum Direction{
Down,
Left,
Up,
Right
}

(Continued on next question...)

Other Interview Questions