Spiral Order Matrix I

Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.



/**
 * @input A : Read only ( DON'T MODIFY ) 2D integer array ' * @input n11 : Integer array's ( A ) rows
 * @input n12 : Integer array's ( A ) columns
 * 
 * @Output Integer array. You need to malloc memory for result array, and fill result's length in length_of_array
 */
int* spiralOrder(const int** Arr, int n11, int n12, int *length_of_array) {
*length_of_array = n11 * n12; // length of result array
int *result = (int *) malloc(*length_of_array * sizeof(int));
// DO STUFF HERE
int A = 0,B = 0,C = n12-1,D = n11-1;
int dir = 0,i,k=0;
while(A <= D && B <= C)
{
    if(dir == 0)
    {
        for(i = B ; i <= C ; i++)
            result[k++] = Arr[A][i];
        A++;
    }else if(dir == 1){
        for(i = A ; i <= D ; i++)
            result[k++] = Arr[i][C];
        C--;
    }else if(dir == 2){
        for(i = C ; i >= B ; i--)
            result[k++] = Arr[D][i];
             D--;
    }else if(dir == 3){
        for(i = D ; i >= A ; i--)
            result[k++] = Arr[i][B];
        B++;
    }
    dir = (dir + 1)%4;
}
return result;
}

Comments