Sunday 17 July 2016

Spiral Order Matrix I Solution

Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example:
Given the following matrix:
[
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
]
You should return
[1, 2, 3, 6, 9, 8, 7, 4, 5]

 /**  
  * @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** A, 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 top = 0, bottom = n11 - 1, left = 0, right = n12 - 1;  
    int dir = 0, k = 0, i;  
    while(top <= bottom && left <= right){  
      if(dir == 0){  
        for(i = left; i <= right; i++){  
          result[k++] = A[top][i];  
        }  
        top++;  
        dir = 1;  
      } else if(dir == 1){  
        for(i = top; i <= bottom; i++){  
          result[k++] = A[i][right];  
        }  
        right--;  
        dir = 2;  
      } else if(dir == 2){  
        for(i = right; i >= left; i--){  
          result[k++] = A[bottom][i];  
        }  
        bottom--;  
        dir = 3;  
      } else if(dir == 3){  
        for(i = bottom; i >= top; i--){  
          result[k++] = A[i][left];  
        }  
        left++;  
        dir = 0;  
      }  
    }  
    return result;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive