Question 1 Print Matrix Diagonal Up Down:
Input : [[5 8 9 1], [2 7 3 2], [0 5 4 9], [4 8 7 6]] Output : 5 8 2 9 7 0 1 3 5 4 2 4 8 9 7 6 public static void printMatrixDiagonalUpDown(int[][] m){ int N = m.length; for (int i = 0; i<N; i++){ for (int j =i; j>=0; j--){ System.out.print(m[i-j][j] + " "); } System.out.println(); } for (int i = 1; i<N; i++){ for (int j =N-1; j>=i; j--){ System.out.print(m[i+N-1-j][j] + " "); } System.out.println(); } }
Question 2 : Print Matrix Diagonal Down Up Input : [[5 8 9 1], [2 7 3 2], [0 5 4 9], [4 8 7 6]] Output : 5 2 8 0 7 9 4 5 3 1 8 4 2 7 9 6 public void printMatrixDiagonalDownUp(int[][] m){ int N = m.length; for (int i = 0; i<N; i++){ for (int j =0; j<=i; j++){ System.out.print(m[i-j][j] + " "); } System.out.println(); } for (int i = 1; i<N; i++){ for (int j =i; j<=N-1; j++){ System.out.print(m[N-1-j+i][j] + " "); } System.out.println(); } }
No comments :
Post a Comment