forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiagonalMatrix.java
More file actions
61 lines (56 loc) · 2.11 KB
/
Copy pathDiagonalMatrix.java
File metadata and controls
61 lines (56 loc) · 2.11 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
// Time Complexity :O(M*N)
// Space Complexity : O(1) without considering result space.
// Did this code successfully run on Leetcode : Yes
// Three line explanation of solution in plain english
// Your code here along with comments explaining your approach
class DiagonalMatrix {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null) {
throw new IllegalArgumentException("Input matrix is null");
}
if (matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int rows = matrix.length;
int cols = matrix[0].length;
int[] result = new int[rows * cols];
int r = 0;
int c = 0;
boolean up = true;
for (int i = 0; i < result.length; i++) {
result[i] = matrix[r][c];
if(up) { // Move Up
if (c == cols - 1) {
// Reached last column. Now move to below cell in the same column.
// This condition needs to be checked first due to top right corner cell.
r++;
up=false;
} else if (r == 0) {
// Reached first row. Now move to next cell in the same row.
c++;
up=false;
} else {
// Somewhere in middle. Keep going up diagonally.
r--;
c++;
}
} else { // Move Down
if (r == rows - 1) {
// Reached last row. Now move to next cell in same row.
// This condition needs to be checked first due to bottom left corner cell.
c++;
up=true;
} else if (c == 0) {
// Reached first columns. Now move to below cell in the same column.
r++;
up=true;
} else {
// Somewhere in middle. Keep going down diagonally.
r++;
c--;
}
}
}
return result;
}
}