Microsoft Interview Question for Software Engineer in Tests


Team: Windows Hyper-V
Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
3
of 5 vote

public static void printMat(int [][]mat)
	{
		if(mat == null  || mat.length == 0)
			return;

		int offset = 1;
		int row = 0, col = 0;
		while(row != mat.length / 2 && col != mat[0].length / 2) {
			
			while(col < mat[0].length - offset)
				System.out.print(mat[row][col++]+"  ");

			while(row < mat.length - offset)
				System.out.print(mat[row++][col]+"  ");

			while(col >= 0 + offset)
				System.out.print(mat[row][col--]+"  ");

			while(row >= 0 + offset)
				System.out.print(mat[row--][col]+"  ");

			offset++;
			row++;
			col++;
		}
		
		System.out.print(mat[row][col]);

	}

- zcatla June 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 3 vote

This is for general matrix
i.e. it would work for any (n x m) matrix

#include<stdio.h>
#include<conio.h>
#define MAX 30

void display(int[MAX][MAX],int,int);
void spiral (int[MAX][MAX],int,int);

void main()
{
	int i,j,n,m,a[MAX][MAX];
	printf("Enter the number of rows : ");
	scanf("%d",&n);
	printf("Enter the number of columns : ");
	scanf("%d",&m);
	
	printf("Enter the Matrix Elements ");
	for(i=0;i<n;i++){
		printf("\n\nRow : %d \n",(i+1));
		
		for(j=0;j<m;j++){
			scanf("%d",&a[i][j]);
		}
	}
	
	printf("Entered Matrix is : \n");	
	display(a,n,m);
	printf("\n\nSpiral Matrix output: \n\n");	
	spiral(a,n,m);
	getch();	
}

void display(int a[MAX][MAX],int n, int m)
{
	int i,j;
	for(i=0;i<n;i++){
		printf(" \n__________________________________________________\n");
		
		for(j=0;j<m;j++){
			printf("%d\t",a[i][j]);
		}
	}
	printf(" \n__________________________________________________\n");
}


void spiral(int a[MAX][MAX],int n, int m)
{
	int i,j,temp;
	int count = 0;
	
	for(i=0; i<n; i++,count++){
	
		// 1. Horizontal upper row
		for(j=count; j<(m-count); j++){
			printf("%d ", a[i][j]);
		}
		
		// 2. Vertical right column
		for(temp = (i+1); temp<(n-count); temp++){
			printf("%d ", a[temp][j-1]);
		}
				
		temp--;
		//reverse the above 2-steps
		
		// 3.Horizontal lower row
		for(j=j-2; j>=(count); j--){
			printf("%d ", a[temp][j]);
		}
		
		// 4. Vertical left column
		
		j++;
		for(temp = temp-1; temp>count; temp--){
			printf("%d ", a[temp][j]);
		}
		
		printf("\n");
	}
}

Output :

Entered Matrix is :

____________________
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
____________________



Spiral Matrix output:

1 2 3 4 5 6 7 14 21 28 35 34 33 32 31 30 29 22 15 8
9 10 11 12 13 20 27 26 25 24 23 16
17 18 19 18 17
25





.

- priyanshu911 June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
int a[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};
//6X6 matrix initialized from 1-36 so it prints in asending order
int i=0,j=0,left=0,right=5; //we use left and right to traverse through the matrix
int m=6,n=6; //6X6 mXn
cout<<"\n values of the matrix :\n";
for(i=0;i<m;i++)
{
                for(j=0;j<n;j++)
                                cout<<'\t'<<a[i][j];
                cout<<'\n';
}               

cout<<"\n Values of spiral matrix: ";

for(int k=0; k<(m/2+1); k++) // no of times the spiral moves around  its 3 here
{
        for(j=left; j<right; j++)
                    cout<<'\t'<<a[left][j]; //right
        for(i=left; i<right; i++)
                    cout<<'\t'<<a[i][right]; //down
        for(j=right; j>left; j--)
                       cout<<'\t'<<a[right][j]; //left
        for(i=right; i>left;i--)
                       cout<<'\t'<<a[i][left]; //up
        left++; // decrease the size of the spiral
        right--;
        
}
getch();
return 0;
        
}

- Srishti Parakh June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Check out the C solution at w w w.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/

- math.matt June 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Given:
Matrix [M x N]

Logic:
-Have 4 variable columnMin, columnMax, rowMin, rowMax
-Initialize variables as
columnMin = 0
rowMin = 0
columnMax = N
rowMax = M

Loop
if(columnMin != columnMax)
{
Print Row from Matrix [rowMin][columnMin] to Matrix [rowMin] [columnMax]
rowMin ++ ;
}
else
{
break;
}

if(rowMin != rowMin)
{
Print Column from Matrix [rowMin][columnMax] to Matrix [rowMax][columnMax]
columnMax - - ;
}
else
{
break;
}

if(columnMin != columnMax)
{
Print Row from Matrix [rowMax][columnMax] to Matrix [rowMax][columnMin]
rowMax - - ;
}
else
{
break;
}

if(rowMin != rowMin)
{
Print Column from Matrix [rowMax][columnMin] to Matrix [rowMin][columnMin]
columnMin ++ ;
}
else
{
break;
}
END LOOP

- PKT June 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void print_matrix(std::vector<std::vector<int> > matrix)
{ 
    if(matrix.size())
    {
        int m = matrix.size();//number of rows
        int n = matrix[0].size();//number of columns
        int layers_number = std::min((m + 1) / 2, (n + 1) / 2);
        for(int layer = 0; layer < layers_number; ++layer)
        {
            //print top of the layer
            for(int i = layer; i < n - layer; ++i)
                std::cout << matrix[layer][i] << " ";

            //print right part of the layer
            for(int i = layer + 1; i < m - layer; ++i)
                std::cout << matrix[i][n - 1 - layer] << " ";

            //print bottom of the layer
            if(layer < m / 2)
            {
                for(int i = n - 2 - layer; i >= layer; --i)
                    std::cout << matrix[m - 1 - layer][i] << " ";
            }

            //print left part of the layer
            if(layer < n / 2)
            {
                for(int i = m - 2 - layer; i > layer; --i)
                    std::cout << matrix[i][layer] << " ";
            }
        }
    }    
}

- J. June 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Following is my efforts to solve the problem. The solution is written in java.

static void print(int[][] a, int k, int x1, int x2, boolean vertical, boolean reverse) {
		
		if (reverse) {
			for(int i=x2; i>=x1; --i) {
				if (vertical) {
					System.out.print(a[i][k]);
				} else {
					System.out.print(a[k][i]);
				}
			}
			
		} else {
			for(int i=x1; i<=x2; ++i) {
				if (vertical) {
					System.out.print(a[i][k]);
				} else {
					System.out.print(a[k][i]);
				}
			}
		}
	}

	static void print_spiral(int[][] a, int x1, int x2, int y1, int y2) {
		
		if (x1 > x2 || y1 > y2)
			return;
		
		print(a, x1, x1, x2, false, false);
		print(a, y2, y1+1, y2, true, false);
		print(a, x2, x1, x2-1, false, true);
		print(a, y1, y1+1, y2-1, true, true);
		
		print_spiral(a, x1 + 1, x2 - 1, y1 + 1, y2 - 1);
	}

- Laiq Ahmed June 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void spiralMatrix(int** array, int startRow, int startCol, int nrows, int ncols)
{
	if (nrows <=0  || ncols <= 0 )
		return;
   int i = 0;
   for (i = startCol ; i < ncols; i++)
   {
	   printf("%d ", array[startCol][i]);
   }
   for (i = startRow + 1; i < nrows; i++)
   {
	  printf("%d ", array[i][ncols-1]);
   }
   for (i = ncols - 2; i >= startCol;i--)
   {
	   printf("%d ", array[nrows-1][i]);
   }
   for (i = nrows-2; i >= startRow + 1; i--)
   {
	   printf("%d ", array[i][startCol]);
   }
   spiralMatrix(array, startRow + 1, startCol + 1, nrows-1, ncols-1);

}


int main(void)
{
   int i,nrows,ncols,j;

   printf("Enter number of rows and number of columns ");
   scanf("%d %d",&nrows,&ncols);

   int** array;
   array=(int**)malloc(nrows*sizeof(int*));
   for (i=0; i<nrows; i++)
      array[i]=(int*)malloc(ncols*sizeof(int));

   for (i=0; i<nrows; i++)
	   for (j=0; j<ncols; j++)
		   scanf("%d", &array[i][j]);

   for (i=0; i<nrows; i++)
   {
   	   for (j=0; j<ncols; j++)
   	     printf("%d ", array[i][j]);
   	   printf("\n");
   }

   spiralMatrix(array, 0, 0, nrows, ncols);

   for (i=0; i<nrows; i++)
      free((void*)array[i]);
   free((void*)array);


   return 0;
}

- Anonymous June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int a[4][5] = {
                        {1,  2,  3,  4, 5},
                        {14,  15,  16,  17, 6},
                        {13,  20,  19,  18, 7},
                        {12,  11,  10,  9, 8},
                        };

void print_spiral (int r, int c)
{
        int i = 0;
        int j = -1;
        int right_max = c;
        int down_max = r;

        int left_min = -1;
        int up_min = 0;

        int total_count = r * c;

        while (total_count > 0)
        {
                i = up_min;
                j++;
                while (j < right_max && total_count > 0)
                {
                        printf ("%d \n", a[i][j]);
                        j++;
                        total_count--;
                }
                right_max--;

                j = right_max;
                i++;
                while (i < down_max && total_count > 0)
                {
                        printf ("%d \n", a[i][j]);
                        i++;
                        total_count--;
                }
                down_max--;

                i = down_max;
                j--;
                while (j > left_min && total_count > 0)
                {
                        printf ("%d \n", a[i][j]);
                        j--;
                        total_count--;
                }
                left_min++;

                j = left_min;
                i--;
                while (i > up_min && total_count > 0)
                {
                        printf ("%d \n", a[i][j]);
                        i--;
                        total_count--;
                }
                up_min++;
        }
}
int main ()
{
        print_spiral(4, 5);
}

- SK June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The solution works for m * n matrix no metter m is equl or not equal to n.

enum Direction {
	L2R(1, 0), T2B(0, 1), R2L(-1, 0), B2T(0, -1);
	int xDelta;
	int yDelta;

	private Direction(int xDelta, int yDelta) {
		this.xDelta = xDelta;
		this.yDelta = yDelta;
	}
}

public void processArray(int[][] arr) {
	if (arr == null) {
		return;
	}

	int w = arr[0].length;
	int h = arr.length;
	int layers = Math.min(w, h) / 2;
	for (int layer = 0; layer < layers; ++layer) {
		processStrip(arr, layer, layer, w - 2 * layer - 1, Direction.L2R);
		processStrip(arr, w - layer - 1, layer, h - 2 * layer - 1, Direction.T2B);
		processStrip(arr, w - layer - 1, h - layer - 1, w - 2 * layer - 1, Direction.R2L);
		processStrip(arr, layer, h - layer - 1, h - 2 * layer - 1, Direction.B2T);
	}

	Direction dir = w >= h ? Direction.L2R : Direction.T2B;
	int count = (h - 2 * layers) * (w - 2 * layers);
	processStrip(arr, layers, layers, count, dir);
}

public void processStrip(int[][] arr, int x, int y, int count, Direction dir) {
	while (count-- > 0) {
		System.out.print(arr[y][x] + ", ");
		x += dir.xDelta;
		y += dir.yDelta;
	}
}

- Anonymous June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void printSpiral(int **a,int m,int n)
{
    int i=0,j=0,p,q;
    p=m;
    q=n;
    while(p>0 && q>0)
    {
        while(j<q)
        {
            printf("%d ",a[i][j]);
            j++;
        }
    j--;
    i++;
    while(i<p)
        {
            printf("%d ",a[i][j]);
            i++;
        }
    i--;
    j--;
    while(j>=(n-q))
    {
        printf("%d ",a[i][j]);
        j--;
    }
    j++;
    i--;
    while(i>m-p)
    {
        printf("%d ",a[i][j]);
        i--;
    }
    i++;
    j++;
    p--;
    q--;

}

- Joey June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int[] getSpiral( int[][] m ){		
		
		int circleIndex = 0;
		
		int totalCirclesCount = m.length/2;
		
		int index = 0;
		int[] arr  = new int[m.length * m.length];
		
		while( circleIndex < totalCirclesCount ){
			
			for( int col = circleIndex; col < m.length-circleIndex-1; col++ ){				
				arr[index++] = m[circleIndex][col];				
			}
			
			for( int row = circleIndex; row < m.length-circleIndex-1; row++){
				arr[index++] = m[row][m.length-circleIndex-1];	
			}
			
			for( int col = m.length-1-circleIndex; col > circleIndex; col-- ){
				arr[index++] = m[m.length-1-circleIndex][col];
			}
			
			for( int row = m.length-1-circleIndex; row > circleIndex; row--){
				arr[index++] = m[row][circleIndex];
			}
			
			++circleIndex;
		}
			
		
		int middle = m.length/2;
		
		// 'odd' matrix size 
		if( (m.length & 1) == 1 ){
			arr[index] = m[middle][middle];
		}		
		
		return arr;
		
	}

- m@}{ June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

while((leftEnd <= rightEnd) && (upEnd <= downEnd)){
for(int i=leftEnd;i<=rightEnd;i++){
System.out.print(matrix[upEnd][i]+" ");
}
upEnd++;
for(int i=upEnd;i<=downEnd;i++){
System.out.print(matrix[i][rightEnd]+" ");
}
rightEnd--;
for(int i=rightEnd;i>=leftEnd;i--){
System.out.print(matrix[downEnd][i]+" ");
}
downEnd--;
for(int i=downEnd;i>=upEnd;i--){
System.out.print(matrix[i][leftEnd]+" ");
}
leftEnd++;
}

- Anonymous June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>


void printspiral(int ar[5][6],int rowstart,int rowend,int colstart,int colend)
{
   int i;
     if(rowstart <= rowend  && colstart <=colend)
       {
           
            if(rowstart == rowend)
              {
                 
                  for(i=colstart;i<=colend;i++)
                   printf("%d  ",ar[rowstart][i]);
                   return; 

              }


              if(colstart == colend)
              {
                 
                  for(i=colstart;i<=colend;i++)
                   printf("%d  ",ar[i][colstart]);

                   return;
              }
        
              for(i=colstart;i<=colend;i++)
               { printf("%d  ",ar[rowstart][i]);}

              rowstart++;
            
              for(i=rowstart;i<=rowend;i++)
               { printf("%d  ",ar[i][colend]);}

              colend-- ;

              for(i=colend;i>=colstart;i--)
               { printf("%d  ",ar[rowend][i]);}

               --rowend;

              for(i=rowend;i>=rowstart;i--)
                { printf("%d  ",ar[i][colstart]);}
          
               ++colstart;
            

              
              printspiral(ar,rowstart,rowend,colstart,colend);



        }

}


int main()
{
   int ar[5][6]={ {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}
                };

   int rowstart=0;
   int rowend =4;
   int colstart = 0;
   int colend =5;

   printspiral(ar,rowstart,rowend,colstart,colend);
            

  } 


output :1  2  3  4  5  6  12  18  24  30  29  28  27  26  25  19  13  7  8  9  10  11  17  23  22  21  20  14  15  16

- Ravi June 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this will work for M*N also

- Ravi June 27, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

One more solution in cpp :-)

#include <iostream>
using namespace std;
enum State{RIGHT,DOWN,LEFT,UP};
State goRight(int arr[][5],int &col,int &row,int &colStart, int &colEnd, int &rowStart, int &rowEnd)
{
	//if(col<=colEnd&&col>=colStart)
		col++;
	cout<<arr[row][col];
	if(col == colEnd)
	{
		rowStart++;
		return DOWN;
	}
	return RIGHT;
}
State goDown(int arr[][5],int &col,int &row,int &colStart, int &colEnd, int &rowStart, int &rowEnd)
{
	//if(row<=rowEnd&&row>=rowStart)
		row++;
	cout<<arr[row][col];
	if(row == rowEnd)
	{
		colEnd--;
		return LEFT;
	}
	return DOWN;
}
State goLeft(int arr[][5],int &col,int &row,int &colStart, int &colEnd, int &rowStart, int &rowEnd)
{
	//if(col<=colEnd&&col>=colStart)
		col--;
	cout<<arr[row][col];
	if(col == colStart)
	{
		rowEnd--;
		return UP;
	}
	return LEFT;
}
State goUP(int arr[][5],int &col,int &row,int &colStart, int &colEnd, int &rowStart, int &rowEnd)
{
	//if(row<=rowEnd&&row>=rowStart)
		row--;
	cout<<arr[row][col];
	if(row == rowStart)
	{
		colStart++;
		return RIGHT;
	}
	return UP;
}
void printArr(int arr[][5],int cols,int rows)
{
	State state = RIGHT;
	int colStart=0,colEnd=cols-1;
	int rowStart=0,rowEnd=rows-1;
	int col=0,row=0;
	cout << arr[row][col];
	while(colStart<=colEnd&&rowStart<=rowEnd)
	{
		switch(state)
		{
		case RIGHT:
			state=goRight(arr,col,row,colStart,colEnd,rowStart,rowEnd);
			break;
		case DOWN:
			state=goDown(arr,col,row,colStart,colEnd,rowStart,rowEnd);
			break;
		case LEFT:
			state=goLeft(arr,col,row,colStart,colEnd,rowStart,rowEnd);
			break;
		case UP:
			state=goUP(arr,col,row,colStart,colEnd,rowStart,rowEnd);
			break;
		}
	}
}

- anim June 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void PrintMatrixInSpiralOrder(int[][] matrix)
{
	List<int> result = GetMatrixInSpiralOrder(matrix, 0, 0, matrix.GetLength(0)-1, matrix.GetLength(1)-1);
	
	if (result.Count > 0)
	{
		Console.Write(result[0]);
		for (int i=1;i < result.Count;i++)
			Console.Write(string.Format(" {0}", result[i]));
	} 
}

private List<int> PrintMatrixInSpiralOrder(int[][] matrix, int startRow, int startCol, int endRow, int endCol)
{
	List<int> values = new List<int>();

	if (startRow > endRow || startCol > endCol)
		return values;

	//first row
	for(int i=startCol;i<=endCol;i++)
		values.Add(matrix[startRow, i]);

	//last col
	for(int i=startRow;i<=endRow;i++)
		values.Add(matrix[i, endCol]);

	//last row
	for(int i=endCol-1;i>=startCol;i--)
		values.Add(matrix[endRow, i]);

	//first col
	for(int i=endRow-1;i>=startCol+1;i--)
		values.Add(matrix[i, startCol]);

	startRow += 1;
	startCol += 1;
	endRow -= 1;
	endCol -= 1;
	
	List<int> resultOfInside = PrintMatrixInSpiralOrder(matrix, startRow, startCol, endRow, endCol);
	return values.AddRange(resultOfInside);
}

- Philip July 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The output of the matrix is very simple, just it:

for (int s = 0; m.size()-s > 0 && m[0].size() - s > 0; s++)
		{
			//h forward
			for (int j = s, i = s; j < (m.size() -s); j++)
					cout << m[i][j] << " ";
			//v down
			for (int i = s+1, j = (m.size()-1-s); i < (m[0].size ()-1-s); i++)
				cout << m[i][j] <<" ";
			//h back
			for (int j = (m.size()-1-s), i = (m[0].size() - 1-s); j > s; j--)
				cout << m[i][j] <<" ";
			//v up
			for (int i = (m[0].size()-1-s), j = s; i > s; i--)
				cout << m[i][j] <<" ";
		}

- Alex July 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Turned out to be simpler than I thought. Hope I am not missing something. Here is the code in java:

public class Matrixspiral {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[][] matrixarr = new int[5][4];
		matrixarr[0] = new int[]{3,2,1,0};
		matrixarr[1] = new int[]{7,-2,3,9};
		matrixarr[2] = new int[]{8,4,-9,2};
		matrixarr[3] = new int[]{0,-3,-4,-5};
		matrixarr[4] = new int[]{9,5,3,1};		
		printRound(matrixarr,0,matrixarr[0].length-1,matrixarr.length-1,0);
		
	}
	private static void printRound(int[][] inparr, int frow,int lcol,  int lrow, int fcol){
		for(int j=fcol;j<=lcol;j++){
			System.out.println(inparr[frow][j]);
		}
		for(int i=frow+1;i <=lrow;i++){
			System.out.println(inparr[i][lcol]);
		}
		for(int j = lcol-1;j >=fcol;j--){
			System.out.println(inparr[lrow][j]);
		}
		for(int i=lrow-1;i >=frow+1;i--){
			System.out.println(inparr[i][fcol]);
		}
		if(lcol-1 < 0 || lrow-1 <0)
			return;
		printRound(inparr,frow+1,lcol-1,lrow-1,fcol+1);
	}

}

- sk July 31, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My solution uses state machine that can change direction of move based on current direction

public enum Direction
    {
        Right,
        Down,
        Up,
        Left
    }

    public class MatrixSpiral
    {
        int[,] _matrix;
        bool[,] _visited;
        int _rowCount, _columnCount, _cellCount;

        public MatrixSpiral(int[,] matrix)
        {
            _matrix = matrix;
            _rowCount = _matrix.GetUpperBound(0) + 1;
            _columnCount = _matrix.GetUpperBound(1) + 1;
            _cellCount = _rowCount * _columnCount;
            
        }

        Direction _currentDirection;
        public void PrintSpiral()
        {
            _currentDirection = Direction.Right;
            _visited = new bool[_rowCount, _columnCount];
            int row = 0;
            int col = 0;
            Console.WriteLine(_matrix[0, 0]);
            _visited[0, 0] = true;
            for (int i = 1; i < _cellCount; i++)
            {
                MoveNext(ref row, ref col);
                Console.WriteLine(_matrix[row, col]);
                _visited[row, col] = true;
            }
        }

        public void MoveNext(ref int row, ref int column)
        {
            int newRow, newCol;
            switch (_currentDirection)
            {
                case Direction.Right: newRow = row; newCol = column + 1;
                    if (!IsValidPosition(newRow, newCol))
                    {
                        _currentDirection = Direction.Down;
                        MoveNext(ref row, ref column);
                    }
                    else
                    {
                        row = newRow;
                        column = newCol;
                    }
                    break;

                case Direction.Down: newRow = row + 1; newCol = column;
                    if (!IsValidPosition(newRow, newCol))
                    {
                        _currentDirection = Direction.Left;
                        MoveNext(ref row, ref column);
                    }
                    else
                    {
                        row = newRow;
                        column = newCol;
                    }

                    break;

                case Direction.Left: newRow = row; newCol = column - 1;
                    if (!IsValidPosition(newRow, newCol))
                    {
                        _currentDirection = Direction.Up;
                        MoveNext(ref row, ref column);
                    }
                    else
                    {
                        row = newRow;
                        column = newCol;
                    }

                    break;

                case Direction.Up: newRow = row - 1; newCol = column;
                    if (!IsValidPosition(newRow, newCol))
                    {
                        _currentDirection = Direction.Right;
                        MoveNext(ref row, ref column);
                    }
                    else
                    {
                        row = newRow;
                        column = newCol;
                    }

                    break;
            }
        }

        public bool IsValidPosition(int row, int column)
        {
            if (row >= _rowCount
             || row < 0
             || column >= _columnCount
             || column < 0
             || _visited[row, column])
                return false;
            else
                return true;

        }
    }

int[,] matrix = new int[,]{ {1,2,3}, {10,11,4}, {9,12,5}, {8,7,6} };
MatrixSpiral spiral = new MatrixSpiral(matrix);
spiral.PrintSpiral();

- vstudio August 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Java for any m*n matrix

public class SpiralMatrix {
	
	public static void main(String[] args) {
		Spiral s = new Spiral(5, 5);
		
		s.PrintMatrix();
		System.out.println("\nThe output is:\n");
		s.PrintSpiral();
		System.out.println();
	}
}

class Spiral {
	int[][] matrix;
	
	Spiral(int m, int n) {
		
		matrix = new int[m][n];
		
		for(int i = 0; i < m; i++) {
			for(int j = 0; j < n; j++) {
				matrix[i][j] = ((i * m) + j + 1) % 10;		
			}
		}
	}
	
	public void PrintMatrix() {
		for(int i = 0; i < matrix.length; i++) {
			System.out.print("[");
			for(int j = 0; j < matrix[0].length; j++) {
				System.out.print(" " + matrix[i][j]);
			}
			System.out.println(" ]");
		}
	}
	
	public void PrintSpiral() {
		for(int offset = 0; offset < matrix[0].length - offset; offset++) {
			
			if (offset <= matrix.length / 2)
				for(int i = offset; i < matrix[0].length - offset; i++) {
					System.out.print(" " + matrix[offset][i]);
				}
			
			if (offset <= matrix[0].length / 2)
				for(int i = offset + 1; i < matrix.length - offset; i++) {
					System.out.print(" " + matrix[i][matrix[0].length - offset - 1]);
				}
	
			if (offset < matrix.length / 2)
				for(int i = matrix[0].length - offset - 2; i >= offset; i--) {
					System.out.print(" " + matrix[matrix.length - offset - 1][i]);
				}
			
			if (offset < matrix[0].length / 2)
				for(int i = matrix.length - offset - 2; i > offset; i--) {
					System.out.print(" " + matrix[i][offset]);
				}
		}
	}	
}

[ 1 2 3 4 5 ]
[ 6 7 8 9 0 ]
[ 1 2 3 4 5 ]
[ 6 7 8 9 0 ]
[ 1 2 3 4 5 ]

The output is:

1 2 3 4 5 0 5 0 5 4 3 2 1 6 1 6 7 8 9 4 9 8 7 2 3

- SJ Park October 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is a simple version of Java code. The idea is to have four indexes: top, down, left and right which are gonna be used to point where we are gonna start printing rows and columns, when top > down or left > right then we are done.

public static void spiralOrder(int[][] matrix) {
    if(matrix.length == 0)
      return;
    // Initialize our four indexes
    int top = 0;
    int down = matrix.length - 1; //number of row
    int left = 0;
    int right = matrix[0].length - 1; //number of col

    while(true)
    {
      // Print top row
      for(int j = left; j <= right; ++j)
        System.out.print(matrix[top][j] + " ");
      top++;

      //end condition
      if(top > down || left > right) break;
      //Print the rightmost column
      for(int i = top; i <= down; ++i) 
        System.out.print(matrix[i][right] + " ");
      right--;
      
      if(top > down || left > right) break;
      //Print the bottom row
      for(int j = right; j >= left; --j) 
        System.out.print(matrix[down][j] + " ");
      down--;
      
      if(top > down || left > right) break;
      //Print the leftmost column
      for(int i = down; i >= top; --i) 
        System.out.print(matrix[i][left] + " ");
      left++;
      
      if(top > down || left > right) break;
    }
  }

- keepworking January 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is my Ruby solution:

#!/usr/bin/env ruby

a = 
[
  [ 1, 2, 3, 4, 5 ],
  [ 6, 7, 8, 9, 0 ],
  [ 1, 2, 3, 4, 5 ],
  [ 6, 7, 8, 9, 0 ],
  [ 1, 2, 3, 4, 5 ]
]

m = a.length
n = a[0].length
b = []
m.times{b << Array.new(n,0)}

s = []
j,k = 0,0
dj,dk = 0,1
kmin,jmin = 0,0
kmax,jmax = n-1,m-1
while true do  
  break if b[j][k] == 1
  s << a[j][k]
  b[j][k] = 1
  if k + dk > kmax
    dk = 0
    dj = 1
    jmin += 1
  elsif k + dk < kmin
    dk = 0
    dj = -1
    jmax -= 1
  elsif j + dj > jmax
    dk = -1
    dj = 0
    kmax -= 1
  elsif j + dj < jmin
    dk = 1
    dj = 0
    kmin += 1
  end
  j += dj
  k += dk
end

p s

- Byron Formwalt April 13, 2014 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More