Today we will write a program to print a given matrix in diagonal order.

 

        public void DiagonalOrder(int[,] input)
        {
            int rowcount = input.GetLength(0);
            int columnCount = input.GetLength(1);
            int rowIndex = -1;
            int columnIndex = 0;
            int startRowIndex = rowIndex;
            int startColumnIndex = columnIndex;
            while (true)
            {
                if (rowIndex < rowcount - 1)
                {
                    rowIndex++;
                }
                else if (rowIndex == rowcount - 1 && columnIndex < columnCount - 1)
                {
                    columnIndex++;
                }
                else if (rowIndex == rowcount - 1 && columnIndex == columnCount - 1)
                {
                    break;
                }
                startRowIndex = rowIndex;
                startColumnIndex = columnIndex;
                while (startRowIndex < rowcount && startRowIndex >= 0
                        && startColumnIndex < columnCount && startColumnIndex >= 0)
                {
                    Console.Write(input[startRowIndex, startColumnIndex] + " , ");
                    startRowIndex = startRowIndex - 1;
                    startColumnIndex = startColumnIndex + 1;

                }
                Console.WriteLine("");
            }
        }
 
input

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 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

output

1 ,
11 , 2 ,
21 , 12 , 3 ,
31 , 22 , 13 , 4 ,
41 , 32 , 23 , 14 , 5 ,
42 , 33 , 24 , 15 , 6 ,
43 , 34 , 25 , 16 , 7 ,
44 , 35 , 26 , 17 , 8 ,
45 , 36 , 27 , 18 , 9 ,
46 , 37 , 28 , 19 , 10 ,
47 , 38 , 29 , 20 ,
48 , 39 , 30 ,
49 , 40 ,
50 ,

————————————————————————————————————————

input

11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45
51 52 53 54 55
16 17 18 19 20
26 27 28 29 30
36 37 38 39 40
46 47 48 49 50

Output

11 ,
21 , 12 ,
31 , 22 , 13 ,
41 , 32 , 23 , 14 ,
51 , 42 , 33 , 24 , 15 ,
16 , 52 , 43 , 34 , 25 ,
26 , 17 , 53 , 44 , 35 ,
36 , 27 , 18 , 54 , 45 ,
46 , 37 , 28 , 19 , 55 ,
47 , 38 , 29 , 20 ,
48 , 39 , 30 ,
49 , 40 ,
50 ,