forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem2.java
More file actions
92 lines (75 loc) · 2.42 KB
/
problem2.java
File metadata and controls
92 lines (75 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//We traverse the matrix in a zigzag diagonal order:
//
//Use row r and column c to track current position.
//
//Use a boolean dir:
//
// true → moving up-right
//
//false → moving down-left
//
//Handle boundary conditions:
//
//When hitting top, bottom, left, or right edge → change direction.
//
//Time: O(m × n)
//Space: O(1) (excluding result)
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
// Number of rows
int m = mat.length;
// Number of columns
int n = mat[0].length;
// Result array to store diagonal traversal
int[] result = new int[m * n];
// Starting position (top-left corner)
int r = 0, c = 0;
// Direction flag:
// true = moving up-right
// false = moving down-left
boolean dir = true;
// Traverse all elements in matrix
for(int i = 0; i < m * n; i++) {
// Store current element in result
result[i] = mat[r][c];
// If moving up-right
if(dir) {
// If reached last column → can only move down
if(c == n - 1) {
r++; // move down
dir = false; // change direction
}
// If reached first row → can only move right
else if(r == 0) {
c++; // move right
dir = false; // change direction
}
// Normal up-right movement
else {
r--; // move up
c++; // move right
}
}
// If moving down-left
else {
// If reached last row → can only move right
if(r == m - 1) {
c++; // move right
dir = true; // change direction
}
// If reached first column → can only move down
else if(c == 0) {
r++; // move down
dir = true; // change direction
}
// Normal down-left movement
else {
r++; // move down
c--; // move left
}
}
}
// Return final diagonal traversal
return result;
}
}