Monday, July 4, 2016

54. Spiral Matrix

I thought it's easy in first place and tried to solve it by simply save up (0 to cols-2), right (0 to rows-2), bottom (cols-1 to 1), left (rows-1 to 1) numbers and goes into inner loop. However, this solution is wrong if there is only one number (output will be empty) or there is just one row or one column (there will be duplicated numbers) in the matrix.
We can modify the implementation based on the idea above. We can track the rowBegin, rowEnd, colBegin and colEnd. After scanning a row/column, we update the one of these four variables such that we can avoid duplicates.

1:  class Solution {  
2:  public:  
3:    vector<int> spiralOrder(vector<vector<int>>& matrix) {  
4:      vector<int> res;  
5:      if (matrix.size() == 0) return res;  
6:      int rows = matrix.size();  
7:      int cols = matrix[0].size();  
8:      int rowBegin = 0, rowEnd = rows-1;  
9:      int colBegin = 0, colEnd = cols-1;  
10:      while (rowBegin <= rowEnd && colBegin <= colEnd) {  
11:        for (int j = colBegin; j <= colEnd; j++) res.push_back(matrix[rowBegin][j]);  
12:        rowBegin++;  
13:        for (int i = rowBegin; i <= rowEnd; i++) res.push_back(matrix[i][colEnd]);  
14:        colEnd--;  
15:        if (rowBegin <= rowEnd) {  
16:          for (int j = colEnd; j >= colBegin; j--) res.push_back(matrix[rowEnd][j]);  
17:          rowEnd--;  
18:        }  
19:        if (colBegin <= colEnd) {  
20:          for (int i = rowEnd; i >= rowBegin; i--) res.push_back(matrix[i][colBegin]);  
21:          colBegin++;  
22:        }  
23:      }  
24:      return res;  
25:    }  
26:  };  

No comments:

Post a Comment