Microsoft Interview Question
Software Engineer / DevelopersSorry for bad formatting.
The idea is.
1. Print the top row and then increment the rowStart by one.
2. Then Print the right most column and decrement the colsEnd by one.
3. Print the bottom row and decrement the rowsEnd by one
4. Print the left most column and increment the colsStart by 1.
5. Do this recursively.
I hv put extra check to for this algo to support rectangular matrix
Any feedback is welcome.
Thanks
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;
}
Here is my output for a sample run:
ARRAY:
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 43 44 45 46 47 48
49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
65 66 67 68 69 70 71 72
73 74 75 76 77 78 79 80
SPIRAL:
57
56 58
55 31 59
54 30 32 60
53 29 13 33 61
52 28 12 14 34 62
51 27 11 03 15 35 63
50 26 10 02 04 16 36 64
49 25 09 01 05 17 37 65
80 48 24 08 06 18 38 66
79 47 23 07 19 39 67
78 46 22 20 40 68
77 45 21 41 69
76 44 42 70
75 43 71
74 72
73
And for the interested, the code (It's messy):
// SpiralArray.c
// (c) souravgh@usc.edu
// Sun Feb 27 1130
// Prints a 2D array spirally.
#include <cstdlib>
#include <cstdio>
using namespace std;
#define RowsInt 10
#define ColsInt 8
typedef struct {
int xPosInt;
int yPosInt;
int noInt;
} Point;
#define ExchangePoints(p1, p2) {\
Point tempPoint = p1;\
p1 = p2; \
p2 = tempPoint; \
}
enum Direction {LeftUp, RightUp, RightDown, LeftDown};
void updateXY (int *xIntPtr, int *yIntPtr, Direction direction) {
int xDxInt = (direction == LeftUp || direction == LeftDown) ? -1 : 1;
int yDyInt = (direction == LeftUp || direction == RightUp) ? -1 : 1;
*xIntPtr += xDxInt;
*yIntPtr += yDyInt;
}
void calculateSpiralCoords (Point *pointPtr, int sizeInt) {
int lastXInt = 0, lastYInt = 0, countInt = 1;
Direction dirsPtr[4] = {LeftUp, RightUp, RightDown, LeftDown};
int currentDirectionInt = 0;
// Calculate the x,y positions of the points
// as if we are about to plot a 2D polygon graph.
for (int indexInt = 0; indexInt < sizeInt; ) {
for (int updateCountInt = 0; updateCountInt < countInt && indexInt < sizeInt; updateCountInt++) {
pointPtr[indexInt].xPosInt = lastXInt;
pointPtr[indexInt].yPosInt = lastYInt;
updateXY (&lastXInt, &lastYInt, dirsPtr[currentDirectionInt]);
indexInt++;
}
currentDirectionInt = (currentDirectionInt + 1) % 4;
if (currentDirectionInt % 2 == 0) {
countInt++;
}
}
// Do some base offset additions to all points.
// This brings all coordinates into +ve values.
// This could have been done in the same loop above,
// but enough was already being done there!
int minXInt = 0, minYInt = 0;
// Find the minimum x and y positions.
for (int indexInt = 0; indexInt < sizeInt; indexInt++) {
minXInt = (minXInt > pointPtr[indexInt].xPosInt) ? pointPtr[indexInt].xPosInt : minXInt;
minYInt = (minYInt > pointPtr[indexInt].yPosInt) ? pointPtr[indexInt].yPosInt : minYInt;
}
// minXInt and minYInt are now 0 or -ve.
// Offset all points.
for (int indexInt = 0; indexInt < sizeInt; indexInt++) {
pointPtr[indexInt].xPosInt -= minXInt;
pointPtr[indexInt].yPosInt -= minYInt;
}
}
void sortPoints (Point *pointPtr, int sizeInt) {
// Do a simple bubble sort to sort the points.
for (int iIndexInt = 0; iIndexInt < sizeInt; iIndexInt++) {
for (int jIndexInt = 0; jIndexInt < sizeInt - iIndexInt - 1; jIndexInt++) {
if (pointPtr[jIndexInt].yPosInt > pointPtr[jIndexInt + 1].yPosInt ||
(pointPtr[jIndexInt].yPosInt == pointPtr[jIndexInt + 1].yPosInt &&
pointPtr[jIndexInt].xPosInt > pointPtr[jIndexInt + 1].xPosInt)) {
ExchangePoints (pointPtr[jIndexInt], pointPtr[jIndexInt + 1]);
}
}
}
}
void plotPoints (Point *pointPtr, int sizeInt ,FILE *outFilePtr) {
// First we space out the points along the X axis.
for (int indexInt = 0; indexInt < sizeInt; indexInt++) {
pointPtr[indexInt].xPosInt *= 3;
}
for (int indexInt = 0; indexInt < sizeInt; ) {
int currYInt = pointPtr[indexInt].yPosInt;
int currXOffset = pointPtr[indexInt].xPosInt;
fprintf (outFilePtr, "%*s", currXOffset, " ");
for (; currYInt == pointPtr[indexInt].yPosInt && indexInt < sizeInt; indexInt++) {
fprintf (outFilePtr, "%*s%02d", pointPtr[indexInt].xPosInt - currXOffset, " ", pointPtr[indexInt].noInt);
currXOffset = pointPtr[indexInt].xPosInt;
}
fprintf (outFilePtr, "\n");
}
}
void printSpiral (int arrIntPtrPtr[RowsInt][ColsInt]) {
Point pointPtr[RowsInt * ColsInt];
fprintf (stdout, "\nARRAY: \n\n");
for (int yIndexInt = 0; yIndexInt < RowsInt; yIndexInt++) {
for (int xIndexInt = 0; xIndexInt < ColsInt; xIndexInt++) {
pointPtr[yIndexInt * ColsInt + xIndexInt].noInt = arrIntPtrPtr[yIndexInt][xIndexInt];
fprintf (stdout, "%3d ", arrIntPtrPtr[yIndexInt][xIndexInt]);
}
fprintf (stdout, "\n");
}
fprintf (stdout, "\nSPIRAL: \n\n");
// Calculate the spiral 2D coordinates.
calculateSpiralCoords (pointPtr, RowsInt * ColsInt);
// Sort the points by Y and break ties for same Y using X.
sortPoints (pointPtr, RowsInt * ColsInt);
// Plot points to stdout
plotPoints (pointPtr, RowsInt * ColsInt, stdout);
}
int main (void) {
int arrIntPtrPtr[RowsInt][ColsInt];
for (int yIndexInt = 0; yIndexInt < RowsInt; yIndexInt++) {
for (int xIndexInt = 0; xIndexInt < ColsInt; xIndexInt++) {
// Increasing ints.
arrIntPtrPtr[yIndexInt][xIndexInt] = yIndexInt * ColsInt + xIndexInt + 1;
}
}
printSpiral (arrIntPtrPtr);
return EXIT_SUCCESS;
}
#define ROW 5
#define COL 5
int arr[ROW][COL] = {
{1, 2, 3, 4, 9},
{12, 13, 14, 5, 2},
{11, 16, 15, 6, 23},
{10, 9, 8, 7, 56},
{34, 35, 36, 37, 78}
};
void printArrSpiral(int arr[][COL],int level,int row, int col)
{
int i = 0;
for(i = level; i < col-level; i++)
cout<<arr[level][i]<<" ";
for(i = level+1; i <= row-level-1; i++)
cout<<arr[i][col-level-1]<<" ";
if(row-level-1 > level)
{
for(i = col-level-2; i >= level; i--)
{
cout<<arr[row-level-1][i]<<" ";
}
}
if(col-level-1 > level)
{
for(i = row-level-2; i > level; i--)
cout<<arr[i][level]<<" ";
}
cout<<endl;
}
int main()
{
int row = ROW;
int col = COL;
int level = (row/2 <= col/2)?row/2:col/2;
for(int i = 0; i<= level; i++)
{
printArrSpiral(arr,i,ROW,COL);
}
return 0;
}
Also try this:
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
}
<pre lang="" line="1" title="CodeMonkey25465" class="run-this">public class Matrix
{
private int[][] matrix;
public Matrix(int[][] inputMatrix)
{
matrix = inputMatrix;
}
public void PrintSpirally()
{
for (int i = 0; i < matrix.Length; i++)
{
int startIndex = 0;
int endIndex = matrix[i].Length - 1;
int increment = 1;
//zig zag; even rows go from left to right. odd rows go from right to left
if (i % 2 == 1)
{
increment = -1;
int temp = startIndex;
startIndex = endIndex;
endIndex = temp;
}
while (startIndex != endIndex)
{
Console.Write(matrix[i][startIndex] + ",");
startIndex += increment;
}
Console.Write(matrix[i][startIndex]);
Console.WriteLine();
}
}
}</pre><pre title="CodeMonkey25465" input="yes">
</pre>
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
void print_arr(int **ptr, int n)
{
cout << endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout << setw(2) << ptr[i][j] << " " ;
cout << endl;
}
cout << endl;
}
void printidown(int **ptr, int imin, int imax, int jmin, int jmax)
{
for(int i=imin;i<=imax; i++)
cout<< ptr[i][jmin] << " ";
}
void printiup(int **ptr, int imin, int imax, int jmin, int jmax)
{
for(int i=imax;i>=imin; i--)
cout<< ptr[i][jmax] << " ";
}
void printjright(int **ptr, int imin, int imax, int jmin, int jmax)
{
for(int j=jmin;j<=jmax; j++)
cout<< ptr[imax][j] << " ";
}
void printjleft(int **ptr, int imin, int imax, int jmin, int jmax)
{
for(int j=jmax;j>=jmin; j--)
cout<< ptr[imin][j] << " ";
}
void show_spiral(int **ptr, int n)
{
int imin=0, imax=n-1, jmin=0, jmax=n-1;
while(jmin >= 0 && jmax <= (n-1) && imin >= 0 && imax <= (n-1) && jmin <= jmax && imin <= imax)
{
// print the rows downwards
printidown(ptr, imin, imax, jmin, jmax);
jmin++;
// print the columns from left to right
printjright(ptr, imin, imax, jmin, jmax);
imax--;
// print the columns from left to right
printiup(ptr, imin, imax, jmin, jmax);
jmax--;
// print the columns from left to right
printjleft(ptr, imin, imax, jmin, jmax);
imin++;
}
cout << endl;
}
int main()
{
int n,k=1;
cout << " Enter value for n " << endl ;
cin >> n;
int **ptr = new int*[n];
for(int i=0;i<n;i++)
ptr[i] = new int;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
ptr[i][j]=k++;
cout << " Print the array : " << endl;
print_arr(ptr,n);
cout << " Print the array in spiral form : " << endl;
show_spiral(ptr,n);
return 0;
}
- Paras February 26, 2011