Thursday, December 4, 2014

zigzag print matrix - google interview question

zigzag打印矩阵
e.g.  
input:
a b c
d e f
g h i

output:
adbceghfi



Answer: just simulate the move
 1)start at i=1, j=1
2)move down once(i++) OR move right if you are at the bottom side
3)move in north east direction until you are reached top or right side
4)move right once if you are at top side OR move down once if you are at right side
5)move in south west direction until you are reached bottom or left side
 6)go to step2 if you are still in the range

void print(vector<string>&matrix){
    int row=matrix.size();
    int col=matrix[0].length();
    int i=0,j=0;
    do{
        cout<<matrix[i][j]<<" ";
        if(i<row-1)
            i++;
        else if(j<col-1)
                j++;
        else//already finished printing
            break;
        //NE(north east) direction
        while(i>0&&j<col-1){
            cout<<matrix[i][j]<<" ";
            i--;j++;
        }
        cout<<matrix[i][j]<<" ";
        if(i==0&&j<col-1)
            j++;
        else
            i++;
        while(i<row-1&&j>0){//SW direction
            cout<<matrix[i][j]<<" ";
            i++;j--;
        }
    }while(i<=row-1&&j<=col-1);
    cout<<endl;
}

No comments:

Post a Comment