Interview Questions

Print a matrix spirally

Software QA/Tests Interview Questions from Microsoft


(Continued from previous question...)

Print a matrix spirally

Question:
Print a matrix spirally


maybe an answer:


tested with few cases.
base idea is: we have 4 loops within a big loop; each time we print a row/column, we shrink the matrix (by left boundary, right, up or down: it depends) by 1. <-- in this way we gradually narrow down our matrix...

void print_matrix_spirally(int **m, int r, int c){
int left=0,right=c-1,top=0,down=r-1;
while(left<=right&&top<=down){
bool sw1=false,sw2=false,sw3=false,sw4=false;
for(int i=left;i<=right;i++){
cout<<m[top][i]<<" ";
if(!sw1)
sw1=true;
}
if(sw1)
top++;
for(int i=top;i<=down;i++){
cout<<m[i][right]<<" ";
if(!sw2)
sw2=true;
}
if(sw2)
right--;
for(int i=right;i>=left;i--){
cout<<m[down][i]<<" ";
if(!sw3)
sw3=true;
}
if(sw3)
down--;
for(int i=down;i>=top;i--){
cout<<m[i][left]<<" ";
if(!sw4)
sw4=true;
}
if(sw4)
left++;
}
}

(Continued on next question...)

Other Interview Questions