Skip to content

Commit a1870b3

Browse files
committed
update 498, cheatsheet
1 parent 08dff96 commit a1870b3

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

doc/cheatsheet/matrix.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
- LC 59
1717
- Sparse matrix product
1818
- LC 311
19+
- Diagonal Traverse
20+
- LC 498
1921

2022
- Algorithm
2123
- [fucking algorithm : 二维数组的花式遍历技巧](https://labuladong.github.io/algo/2/20/26/)

leetcode_java/src/main/java/LeetCodeJava/Array/DiagonalTraverse.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,40 @@ public class DiagonalTraverse {
4444
//
4545
// }
4646

47+
// V0-1
48+
// IDEA : matrix op (gpt)
49+
public int[] findDiagonalOrder_0_1(int[][] mat) {
50+
// Edge case: empty matrix
51+
if (mat == null || mat.length == 0 || mat[0].length == 0) {
52+
return new int[0];
53+
}
54+
55+
int rows = mat.length, cols = mat[0].length;
56+
int[] result = new int[rows * cols];
57+
int index = 0;
58+
59+
// Loop through all possible diagonals (0 to rows + cols - 2)
60+
for (int d = 0; d < rows + cols - 1; d++) {
61+
// Determine starting point for this diagonal
62+
int r = (d % 2 == 0) ? Math.min(d, rows - 1) : Math.max(0, d - cols + 1);
63+
int c = (d % 2 == 0) ? Math.max(0, d - rows + 1) : Math.min(d, cols - 1);
64+
65+
// Traverse the diagonal
66+
while (r >= 0 && r < rows && c >= 0 && c < cols) {
67+
result[index++] = mat[r][c];
68+
if (d % 2 == 0) { // Upward diagonal
69+
r--;
70+
c++;
71+
} else { // Downward diagonal
72+
r++;
73+
c--;
74+
}
75+
}
76+
}
77+
78+
return result;
79+
}
80+
4781
// V1-1
4882
// https://leetcode.com/problems/diagonal-traverse/editorial/
4983
// IDEA: Diagonal Iteration and Reversal

0 commit comments

Comments
 (0)