-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathproblem2.java
More file actions
57 lines (48 loc) · 1.67 KB
/
problem2.java
File metadata and controls
57 lines (48 loc) · 1.67 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
// Time Complexity : O(m*n)
// Space Complexity : O(1) (only output array used)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : Only tricky part is direction change and boundary handling.
// Your code here along with comments explaining your approach in three sentences only
// I move diagonally up-right and down-left alternatively using direction flag.
// Whenever I hit a boundary, I shift to the next valid cell (right or down) and flip direction.
// I continue until I collect all m*n elements.
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[] ans = new int[m * n];
int r = 0, c = 0;
int dir = 1; // 1 means up-right, -1 means down-left
int idx = 0;
while (idx < m * n) {
ans[idx++] = mat[r][c];
// moving up-right
if (dir == 1) {
if (c == n - 1) { // hit right wall
r++;
dir = -1;
} else if (r == 0) { // hit top wall
c++;
dir = -1;
} else {
r--;
c++;
}
}
// moving down-left
else {
if (r == m - 1) { // hit bottom wall
c++;
dir = 1;
} else if (c == 0) { // hit left wall
r++;
dir = 1;
} else {
r++;
c--;
}
}
}
return ans;
}
}