|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +#define ROW 5 |
| 5 | +#define COL 4 |
| 6 | + |
| 7 | +// A utility function to find min of two integers |
| 8 | +int minu(int a, int b) |
| 9 | +{ return (a < b)? a: b; } |
| 10 | + |
| 11 | +// A utility function to find min of three integers |
| 12 | +int min(int a, int b, int c) |
| 13 | +{ return minu(minu(a, b), c);} |
| 14 | + |
| 15 | +// A utility function to find max of two integers |
| 16 | +int max(int a, int b) |
| 17 | +{ return (a > b)? a: b; } |
| 18 | + |
| 19 | +// The main function that prints given matrix in |
| 20 | +// diagonal order |
| 21 | +void diagonalOrder(int matrix[][COL]) |
| 22 | +{ |
| 23 | + // There will be ROW+COL-1 lines in the output |
| 24 | + for (int line=1; line<=(ROW + COL -1); line++) |
| 25 | + { |
| 26 | + /* Get column index of the first element |
| 27 | + in this line of output. |
| 28 | + The index is 0 for first ROW lines and |
| 29 | + line - ROW for remaining lines */ |
| 30 | + int start_col = max(0, line-ROW); |
| 31 | + |
| 32 | + /* Get count of elements in this line. The |
| 33 | + count of elements is equal to minimum of |
| 34 | + line number, COL-start_col and ROW */ |
| 35 | + int count = min(line, (COL-start_col), ROW); |
| 36 | + |
| 37 | + /* Print elements of this line */ |
| 38 | + for (int j=0; j<count; j++) |
| 39 | + printf("%5d ", |
| 40 | + matrix[minu(ROW, line)-j-1][start_col+j]); |
| 41 | + |
| 42 | + /* Print elements of next diagonal on next line */ |
| 43 | + printf("\n"); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// Utility function to print a matrix |
| 48 | +void printMatrix(int matrix[ROW][COL]) |
| 49 | +{ |
| 50 | + for (int i=0; i< ROW; i++) |
| 51 | + { |
| 52 | + for (int j=0; j<COL; j++) |
| 53 | + printf("%5d ", matrix[i][j]); |
| 54 | + printf("\n"); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// Driver code |
| 59 | +int main() |
| 60 | +{ |
| 61 | + int M[ROW][COL] = {{1, 2, 3, 4}, |
| 62 | + {5, 6, 7, 8}, |
| 63 | + {9, 10, 11, 12}, |
| 64 | + {13, 14, 15, 16}, |
| 65 | + {17, 18, 19, 20}, |
| 66 | + }; |
| 67 | + printf ("Given matrix is \n"); |
| 68 | + printMatrix(M); |
| 69 | + |
| 70 | + printf ("\nDiagonal printing of matrix is \n"); |
| 71 | + diagonalOrder(M); |
| 72 | + return 0; |
| 73 | +} |
0 commit comments