Kth diagonal from the top left of a given matrix | Java implementation of the above approach ; Function returns required diagonal ; Initialize values to print upper diagonals ; Initialize values to print lower diagonals ; Traverse the diagonal ; Print its contents ; Driver Code
import java . util . * ; class GFG { static void printDiagonal ( int K , int N , int [ ] [ ] M ) { int startrow , startcol ; if ( K - 1 < N ) { startrow = K - 1 ; startcol = 0 ; } else { startrow = N - 1 ; startcol = K - N ; } for ( ; startrow >= 0 && startcol < N ; startrow -- , startcol ++ ) { System . out . print ( M [ startrow ] [ startcol ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 3 , K = 4 ; int [ ] [ ] M = { { 4 , 7 , 8 } , { 9 , 2 , 3 } , { 0 , 4 , 1 } } ; printDiagonal ( K , N , M ) ; } }