Saturday, August 15, 2015

Leetcode: Spiral Matrix (0ms) Analysis and solution

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For 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].

Analysis:

Logic is not very difficult, but it has lots of trivial things inside. The procedure can be divided into 4 sections and then process the four sections individually. The key here is the boundary control. See following figure for a clear logic and procedure to implement this problem:

In the figure, four index are used to mark the boundary: upper, right, bottom and left. The code according to above procedure:

//////////////////////////////////////////////////////////
// code 0ms
class Solution {
public:
       vector<int> spiralOrder(vector<vector<int>>& matrix) {
              int upper = 0, right = 0, bottom = 0, left = 0;
              vector<int> res;
              //check input
              if (matrix.size() == 0)return res;
              int m = matrix.size(), n = matrix[0].size(), index = 0, Size = m*n;

              while (index < Size + 1){
                     //section 1
                     for (int j = left; j < n - right; j++){
                           res.push_back(matrix[upper][j]);
                           ++index;
                     }
                     upper++;
                     if (index >= Size)return res;

                     //section 2
                     for (int i = upper; i < m - right; i++){
                           res.push_back(matrix[i][n - right - 1]);
                           ++index;
                     }
                     if (index >= Size)return res;
                     right++;

                     //section 3
                     for (int j = n - right - 1; j >= left; j--){
                           res.push_back(matrix[m-bottom-1][j]);
                           ++index;
                     }
                     if (index >= Size)return res;
                     bottom++;

                     //section 4
                     for (int i = m - bottom - 1; i > upper-1; i--){
                           res.push_back(matrix[i][left]);
                           ++index;
                     }
                     if (index >= Size)return res;
                     left++;
              }
              return res;
       }

};



No comments:

Post a Comment