LeetCode 498: Diagonal Traverse
Problem Description
Explanation
To solve this problem, we can traverse the matrix diagonally in two directions: up-right and down-left. We will switch the direction whenever we reach the boundary of the matrix. By keeping track of the current position and direction, we can construct the diagonal order array.
- Initialize variables for the row and column indices, direction flag, and result array.
- Loop through the matrix elements while adding elements to the result array in the diagonal order.
- Update the row and column indices based on the current direction.
- Handle boundary cases to switch the direction.
- Return the resulting diagonal order array.
Time Complexity: O(m * n) - where m is the number of rows and n is the number of columns in the matrix.
Space Complexity: O(m * n) - for storing the diagonal order array.
Solutions
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
if (mat == null || mat.length == 0) {
return new int[0];
}
int m = mat.length;
int n = mat[0].length;
int[] result = new int[m * n];
int row = 0, col = 0, direction = 1;
for (int i = 0; i < m * n; i++) {
result[i] = mat[row][col];
row -= direction;
col += direction;
if (row >= m) { row = m - 1; col += 2; direction = -direction; }
if (col >= n) { col = n - 1; row += 2; direction = -direction; }
if (row < 0) { row = 0; direction = -direction; }
if (col < 0) { col = 0; direction = -direction; }
}
return result;
}
}
Related LeetCode Problems
Loading editor...