498. 对角线遍历(对角线遍历)

  • 思想很重要,以对角线的数目来作为遍历的次数
  • 遍历方向有两种,分别是左下到右上,以及右上到左下,以i%2来分辨
  • 遍历条件可分为两种,分别是在中线之后以及在中线之前。确定不同规律的起始点。
    1. class Solution {
    2. public:
    3. vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
    4. int m = mat.size();
    5. int n = mat[0].size();
    6. vector<int> res;
    7. for (int i = 0; i < m + n - 1; i++) {
    8. if (i % 2) {//这个i%2是遍历的方向
    9. int x = i < n ? 0 : i - n + 1;//这里的i<n代表是前半段还是后半段
    10. int y = i < n ? i : n - 1;
    11. while (x < m && y >= 0) {
    12. res.emplace_back(mat[x][y]);
    13. x++;
    14. y--;
    15. }
    16. } else {
    17. int x = i < m ? i : m - 1;
    18. int y = i < m ? 0 : i - m + 1;
    19. while (x >= 0 && y < n) {
    20. res.emplace_back(mat[x][y]);
    21. x--;
    22. y++;
    23. }
    24. }
    25. }
    26. return res;
    27. }
    28. };