- public class PrintDiagonalMatrix
- {
- static final int ROW = 5;
- static final int COL = 4;
- // min of two numbers
- static int min(int a, int b)
- {
- return (a < b) ? a : b;
- }
- // min of three numbers
- static int min(int a, int b, int c)
- {
- return min(min(a, b), c);
- }
- // max of two numbers
- static int max(int a, int b)
- {
- return (a > b) ? a : b;
- }
- // print matrix in diagonal order
- static void diagonalOrder(int matrix[][])
- {
- for (int line = 1; line <= (ROW + COL - 1); line++)
- {
- int start_col = max(0, line - ROW);
- int count = min(line, (COL - start_col), ROW);
- for (int j = 0; j < count; j++)
- System.out.print(matrix[min(ROW, line) - j - 1][start_col + j] + " ");
- System.out.println();
- }
- }
- // print a matrix
- static void printMatrix(int matrix[][])
- {
- for (int i = 0; i < ROW; i++)
- {
- for (int j = 0; j < COL; j++)
- System.out.print(matrix[i][j] + " ");
- System.out.print("\n");
- }
- }
- public static void main(String[] args)
- {
- int M[][] =
- {
- { 1, 2, 3, 4 },
- { 5, 6, 7, 8 },
- { 9, 10, 11, 12 },
- { 13, 14, 15, 16 },
- { 17, 18, 19, 20 }, };
- System.out.print("Given matrix is \n");
- printMatrix(M);
- System.out.print("\nDiagonal printing of matrix is \n");
- diagonalOrder(M);
- }
- }
Output:
Given matrix is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Diagonal printing of matrix is
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20
Given matrix is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Diagonal printing of matrix is
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20
No comments:
Post a Comment