Anti Diagonals - The Coding Shala
Home >> Interview Questions >> Anti Diagonals
Anti Diagonals Java Solution
Give an N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
Example:
Input:
1 2 3
7 8 9
4 5 6
Return the following :
[
[1],
[2, 4], [3, 5, 7],
[6, 8],
[9]
]
Input :
1 2
3 4
Return the following :
[
[1],
[2, 3],
[4]
]
Anti Diagonals Java Solution
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 | public class Solution { public ArrayList<ArrayList<Integer>> diagonal(ArrayList<ArrayList<Integer>> A) { ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); int N = A.size(); int i = N - 1; while(i>=0){ ArrayList<Integer> tmp = new ArrayList<Integer>(); int row = 0, col = N-i-1; for(int j=0;j<N-i;j++){ tmp.add(A.get(row).get(col)); row++; col--; } ans.add(tmp); i--; } i = N-2; while(i>=0){ int row = N-i-1, col = N-1; ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int j=0;j<=i;j++){ tmp.add(A.get(row).get(col)); row++; col--; } ans.add(tmp); i--; } return ans; } } |
Other Posts You May Like
how can i solve this using array and not using collection framework classes
ReplyDeleteChange ArrayList to Array and all logic and process will be same, since return type is ArrayList so before returning you have to copy Array into ArrayList again that will be additional changes.
Deletehow can we change ArrayList to array having variable columns?
ReplyDeletepublic class Solution {
Deletepublic int[][] diagonal(int[][] a) {
int n = a.length-1;
ArrayList> otp = new ArrayList<>();
for(int i=0; i temp = new ArrayList<>();
int row = 0, col = i;
while(col >= 0) {
temp.add(a[row][col]);
row++;
col--;
}
otp.add(temp);
}
for(int i=1; i temp = new ArrayList<>();
int row = i, col = n-1;
while(row < n) {
temp.add(a[row][col]);
row++;
col--;
}
otp.add(temp);
}
int[][] otpArray = new int[n+n-1][n+n-1];
for(int i=0; i<otp.size(); i++)
for(int j=0; j<otp.get(i).size(); j++)
otpArray[i][j] = otp.get(i).get(j);
return otpArray;
}
}
Its giving :
Delete[1 0 0 ] [2 4 0 ] [5 0 0 ]
But it should:
[1 ] [2 4 ] [3 5 7 ] [6 8 ] [9 ]