Leetcode 498. Diagonal Traverse
Given an m x n
matrix mat
, return an array of all the elements of the array in a diagonal order.
Input: mat = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
m
(number of rows) and n
(number of columns) are such that 1 <= m, n <= 10^4
.To solve this problem, we can traverse the matrix diagonally. We maintain a boolean flag to control the direction of traversal. We will switch directions when we hit boundaries (edges of the matrix).
Here’s how we can break down the solution:
true
means moving upward diagonally and false
means moving downward diagonally.i == 0
), you need to move right (j++
). If you hit the right boundary (j == n-1
), you need to move down (i++
).j == 0
), you need to move down (i++
). If you hit the bottom boundary (i == m-1
), you need to move right (j++
).#include <vector>
std::vector<int> findDiagonalOrder(std::vector<std::vector<int>>& mat) {
if (mat.empty() || mat[0].empty()) return {};
int m = mat.size();
int n = mat[0].size();
std::vector<int> result;
result.reserve(m * n);
int i = 0, j = 0;
bool goingUp = true;
while (result.size() < m * n) {
result.push_back(mat[i][j]);
if (goingUp) {
if (j == n - 1) {
i++; // Hit right boundary, move down
goingUp = false;
} else if (i == 0) {
j++; // Hit top boundary, move right
goingUp = false;
} else {
i--;
j++;
}
} else {
if (i == m - 1) {
j++; // Hit bottom boundary, move right
goingUp = true;
} else if (j == 0) {
i++; // Hit left boundary, move down
goingUp = true;
} else {
i++;
j--;
}
}
}
return result;
}
O(m * n)
- We visit every element exactly once.O(1)
extra space (excluding the space needed for the output array).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?