leetcode

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

0498.cpp (956B)


      1 class Solution {
      2   public:
      3     bool valid(int i, int m, int j, int n) { return i >= 0 && i <= m && j >= 0 && j <= n; }
      4 
      5     void quick_adjust(int &i, int &j, bool &up) {
      6         if (up)
      7             i++;
      8         else
      9             j++;
     10         up = !up;
     11     }
     12 
     13     void move(int &i, int &j, bool &up) {
     14         if (up) {
     15             i--;
     16             j++;
     17         } else {
     18             i++;
     19             j--;
     20         }
     21     }
     22 
     23     vector<int> findDiagonalOrder(vector<vector<int>> &mat) {
     24         vector<int> res;
     25         bool up = true;
     26         int i = 0, j = 0;
     27         int m = mat.size() - 1, n = mat[0].size() - 1;
     28 
     29         while (true) {
     30             res.push_back(mat[i][j]);
     31             if (i == m && j == n) break;
     32 
     33             move(i, j, up);
     34 
     35             if (!valid(i, m, j, n)) {
     36                 quick_adjust(i, j, up);
     37                 while (!valid(i, m, j, n))
     38                     move(i, j, up);
     39             }
     40         }
     41 
     42         return res;
     43     }
     44 };