Print K 'th element in spiral form of matrix | Python3 program for Kth element in spiral form of matrix ; function for Kth element ; Element is in first row ; Element is in last column ; Element is in last row ; Element is in first column ; Recursion for sub - matrix . & A [ 1 ] [ 1 ] is address to next inside sub matrix . ; Driver code
MAX = 100 NEW_LINE def findK ( A , n , m , k ) : NEW_LINE INDENT if ( n < 1 or m < 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( k <= m ) : NEW_LINE INDENT return A [ 0 ] [ k - 1 ] NEW_LINE DEDENT if ( k <= ( m + n - 1 ) ) : NEW_LINE INDENT return A [ ( k - m ) ] [ m - 1 ] NEW_LINE DEDENT if ( k <= ( m + n - 1 + m - 1 ) ) : NEW_LINE INDENT return A [ n - 1 ] [ m - 1 - ( k - ( m + n - 1 ) ) ] NEW_LINE DEDENT if ( k <= ( m + n - 1 + m - 1 + n - 2 ) ) : NEW_LINE INDENT return A [ n - 1 - ( k - ( m + n - 1 + m - 1 ) ) ] [ 0 ] NEW_LINE DEDENT A . pop ( 0 ) NEW_LINE [ j . pop ( 0 ) for j in A ] NEW_LINE return findK ( A , n - 2 , m - 2 , k - ( 2 * n + 2 * m - 4 ) ) NEW_LINE DEDENT a = [ [ 1 , 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 , 17 , 18 ] ] NEW_LINE k = 17 NEW_LINE print ( findK ( a , 3 , 6 , k ) ) NEW_LINE