Knowee
Questions
Features
Study Tools

Write a Python program to print spiral matrix for a given matrix.

Question

Write a Python program to print spiral matrix for a given matrix.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python program that prints a spiral matrix for a given matrix:

def spiralPrint(m, n, a) :
    k = 0; l = 0
 
    while (k < m and l < n) :
        for i in range(l, n) :
            print(a[k][i], end = " ")
             
        k += 1
 
        for i in range(k, m) :
            print(a[i][n - 1], end = " ")
             
        n -= 1
 
        if ( k < m) :
             
            for i in range(n - 1, (l - 1), -1) :
                print(a[m - 1][i], end = " ")
             
            m -= 1
         
        if (l < n) :
            for i in range(m - 1, k - 1, -1) :
                print(a[i][l], end = " ")
             
            l += 1
 
# Test the above function
a = [ [1, 2, 3, 4, 5, 6],
      [7, 8, 9, 10, 11, 12],
      [13, 14, 15, 16, 17, 18] ]
       
spiralPrint(3, 6, a)

This program works by printing the first row from the remaining rows, then the last column from the remaining columns, then the last row from the remaining rows (from right to left), and then the first column from the remaining columns (from bottom to top). We keep doing this while there are rows and columns left to be printed.

This problem has been solved

Similar Questions

Spiral MatrixWrite a Python program to print spiral matrix for a given matrix.Constraints:1<R<101<C<10Example:23number of elements in the array:6elements of array:-1 2 3 4 5 61 2 3 6 5 4

Given a 2D square matrix, print the matrix in a spiral order. Refer to examples for more details. From an interview's point of view, after you scan the matrix in a 2D array, try to print the matrix in a spiral order without using any extra space.Input FormatThe first line of input contains T - the number of test cases. The first line of each test case contains N - the size of the matrix [NxN]. It is followed by N lines each containing N integers - matrix elements.Output FormatFor each test case, print the matrix in a spiral order, separated by newline.Constraints1 <= T <= 1001 <= N <= 100-100 <= ar[i][j] <= 100ExampleInput41121 24 331 2 38 9 47 6 55-44 25 -52 69 -517 22 51 27 -44-79 28 -78 1 -4765 -77 -14 -21 -6-96 43 -21 -20 90Output11 2 3 41 2 3 4 5 6 7 8 9-44 25 -52 69 -5 -44 -47 -6 90 -20 -21 43 -96 65 -79 17 22 51 27 1 -21 -14 -77 28 -78

Write a python program that defines a matrix and prints

Write a C Program to print lower diagonal of a matrix.

Write a  program to print Transpose of a matrix.First, take as input the number of cells of a square Matrix.Next, n inputs will be "n" columns separated by space for each row

1/2

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.