leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0059.cpp (987B)


      1 class Solution {
      2     pair<int, int> offset[4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
      3     int limit_offset[4] = {1, -1, -1, 1};
      4     int limit[4] = {0, 0, 0, 0};
      5 
      6     int &m = limit[2], &n = limit[1];
      7 
      8     bool valid(int i, int j) { return i >= limit[0] && i <= m && j >= limit[3] && j <= n; }
      9 
     10   public:
     11     vector<vector<int>> generateMatrix(int dim) {
     12         vector<vector<int>> res(dim, vector<int>(dim));
     13         int direction = 0;
     14         int cnt = 0;
     15         int size;
     16         int i = 0, j = 0;
     17 
     18         m = n = dim - 1;
     19         size = (m + 1) * (n + 1);
     20 
     21         while (true) {
     22             res[i][j] = ++cnt;
     23             if (cnt == size) break;
     24 
     25             if (!valid(i + offset[direction].first, j + offset[direction].second)) {
     26                 limit[direction] += limit_offset[direction];
     27                 direction = (direction + 1) % 4;
     28             }
     29 
     30             i += offset[direction].first;
     31             j += offset[direction].second;
     32         }
     33 
     34         return res;
     35     }
     36 };