diff --git a/ZigZag.cpp b/ZigZag.cpp new file mode 100644 index 0000000..ca408ef --- /dev/null +++ b/ZigZag.cpp @@ -0,0 +1,73 @@ +#include +#include + +#define ROW 5 +#define COL 4 + +// A utility function to find min of two integers +int minu(int a, int b) +{ return (a < b)? a: b; } + +// A utility function to find min of three integers +int min(int a, int b, int c) +{ return minu(minu(a, b), c);} + +// A utility function to find max of two integers +int max(int a, int b) +{ return (a > b)? a: b; } + +// The main function that prints given matrix in +// diagonal order +void diagonalOrder(int matrix[][COL]) +{ + // There will be ROW+COL-1 lines in the output + for (int line=1; line<=(ROW + COL -1); line++) + { + /* Get column index of the first element + in this line of output. + The index is 0 for first ROW lines and + line - ROW for remaining lines */ + int start_col = max(0, line-ROW); + + /* Get count of elements in this line. The + count of elements is equal to minimum of + line number, COL-start_col and ROW */ + int count = min(line, (COL-start_col), ROW); + + /* Print elements of this line */ + for (int j=0; j