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)


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