-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathAntiDiagonalTraversal.java
36 lines (31 loc) · 1.07 KB
/
AntiDiagonalTraversal.java
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
/*https://practice.geeksforgeeks.org/problems/print-diagonally1623/1*/
class Solution
{
public int[] antiDiagonalPattern(int[][] matrix)
{
// Code here
int[] result = new int[matrix.length*matrix[0].length];
int index = 0, n = matrix.length, m = matrix[0].length;
//initialize variables to the top left element
int rStart = 0, cStart = 0, rEnd = 0, cEnd = 0;
//till we reach the topright corner
while (rStart != n-1 || cStart != m-1)
{
//from start to end, add to the list
for (int i = rStart, j = cStart; i <= rEnd && j >= cEnd; ++i, --j)
result[index++] = matrix[i][j];
//move downwards after reaching top right corner
if (cStart != m-1)
++cStart;
else
++rStart;
//move right after reacing bottom left corner
if (rEnd != n-1)
++rEnd;
else
++cEnd;
}
result[index] = matrix[n-1][m-1];
return result;
}
}