File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
leetcode_java/src/main/java/LeetCodeJava/Array Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 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/ )
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments