# Print a Given Matrix in Spiral form

The problem of printing a given matrix in spiral form involves a unique traversal pattern to display the elements in a visually appealing spiral order. Interviews for computer science and programming frequently involve an algorithmic task that assesses a candidate's efficiency in manipulating 2D arrays.

Imagine a 2D matrix that is full of integers and has an ascending order for each row and column. The objective is to print and traverse among the matrix elements in a spiral pattern, working clockwise from the top-left corner toward the center.

For example, Given a 2D array, print it in spiral form.

Input:

Output:

```1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
```

Explanation: The result is a spiral-formatted matrix.

### Use the following approach to solve the problem:

The algorithm tracks the location, direction, and whether or not a cell has been visited before.

Here is a detailed breakdown of the algorithm:

1. Initialize Parameters:
• Assume that there are R rows and C columns in the matrix.
• To indicate visited cells, create a boolean array of size R x C.
• Assign the starting point in the matrix to the initial position (r, c), facing the designated direction di Direction can be expressed as an index, where 0 denotes right, 1 down, 2 left, and 3 up.
2. Traversal Loop:
• Establish a traversal loop to visit each R x C cell.
• Verify the candidate's next location (cr, cc) in each iteration by considering their present position and direction.
3. Verify Boundaries and Status of Visits:
• Verify that the candidate's position is between the following matrix boundaries: 0 <= cr < R and 0 <= cc < C.
• Furthermore, confirm that the candidate's position has not been visited previously (false; seen[cr][cc]).
4. Update Position:
• Update the current position to (cr, cc) if the candidate is unseen and inside boundaries.
• Mark the location as visited (visited[r][c] = true) at this time.
5. Clockwise Turn:
• It's time to make a clockwise turn if the candidate has been visited or is out of bounds.
• Change the direction di to the subsequent clockwise direction (e.g., up to right, left to up, down to left, and right to down).
• Determine the candidate's new position in light of the revised strategy.
6. Repeat:
• Till all R x C cells are visited, keep repeating the loop.

The algorithm makes sure that the spiral path is followed and, to prevent straying outside of bounds or visiting cells again, it rotates clockwise as needed. It's a methodical way to go through a matrix in a spiral arrangement, going through each cell precisely once.

### Implementation of code:

Output:

Time Complexity: O(N), where N is the input matrix's total number of elements. Each component in the matrix is added to our final response.

Space Complexity: O(N), the auxiliary space, contains the data held in seen and ans.

### Solving the Problem by dividing the matrix into cycles

Use the following approach to solve the problem:

The matrix can be divided into boundaries, squares, and loops to solve the problem. The printing of the outer loop's elements occurs first, in a clockwise fashion, followed by the printing of the inner loop's elements.

Therefore, four loops that print every element can be used to address the problem of printing a loop's elements. Each "for" loop defines the matrix and a single-direction movement. The movement from left to right is represented by the first for loop, the movement from top to bottom by the second crawl, the movement from left to right by the third, and the movement from bottom to up by the fourth.

To solve the problem, follow to the provided steps:

• Create and initialize variables The indexes for beginning rows are k, ending rows are m, starting columns are l, and ending columns are n.
• Continue running a loop until every loop square is written.
• Print the elements of a square in a clockwise way for each outer loop traverse.
• Print the components of the kth row from column index l to n, or the top row, and raise the count of k.
• Print the final column, or n-1th column, from row index k to m, lowering the count of n. This is known as printing the right column.
• If k is less than m, print the elements of the m-1th row from column n-1 to l and reduce the count of m. This is known as printing the bottom row.
• Print the left column; that is, if l < n, output the lth column's elements from m-1st row to k and raise l's count.

Complexity of Time: O(M*N). It takes O(M*M) time to traverse the matrix.

Auxiliary Space: O(1) is the auxiliary space. No additional room is needed.

### Solving the problem using Recursion

Printing the matrix's boundaries iteratively will solve the previously mentioned problem. We reduce the matrix's dimensions with each iteration. Printing the border or loops has the same concept.

• Create a recursive function that accepts a matrix as input and the following variables as parameters: k is the starting row index, m is the ending row index, l is the starting column index, and n is the ending column index.
• Verify that the base cases (beginning index less than or equal to ending index) are met, and then print the boundary elements in a clockwise fashion.
• Print the top row, that is, print the kth row's elements from column index l to n, then raise the k count.
• Print the final or n-1th column from row index k to m, which is the right column, then reduce the n count.
• If k > m, print the elements of the m-1th row from column n-1 to l and reduce the count of m. This is known as printing the bottom row.
• display the left column; that is, if l < n, display the lth column's items from row m to row k, increasing the number of l.
• Recursively call the function with the values of the row and column starting and ending indices.

### Implementation of the Code

Output:

Time Complexity: O(M*N). It takes O(m*n) time to traverse the matrix.

Auxiliary Space: O(1) is the auxiliary space. No additional room is needed.

### Solving using DFS

• create a DFS function that accepts a matrix, cell indices, and direction checks to see whether the cell indices are heading to a legitimate cell that is both inside bounds and not visited. Skip this cell if not.
• print the value of a cell
• Mark the matrix cell that the pointer points to as visited by setting its value to something the matrix does not support. Verify that the surrounding cells are genuine.
• If not, halt the process; if so, carry on. If the direction is given correctly, then verify if the cell on the right is legitimate.
• If so, follow the preceding procedures to DFS to the correct cell; if not, reverse the direction and DFS downward.
• Otherwise, verify that the cell to the down is valid if the direction indicated is down.
• If so, follow the previous procedures to DFS to the cell below; if not, reverse the direction and follow the above steps to DFS leftward.
• Otherwise, determine whether the cell to the left is legitimate if the direction indicated is left.
• If so, follow the same procedures to DFS to the left cell; if not, alter the direction to up and DFS upwards; if the direction is up, then verify that the cell to the up is legitimate.
• If yes, follow the previous procedures to DFS to the upper cell; if not, reverse the direction and follow the above steps to DFS rightward.

### Implementation of Code

Output:

Time Complexity: O(M*N). It takes O(M*N) time to traverse the matrix.

Auxiliary Space: O(1) is the auxiliary space. There is no need for more space (not including the stack that the recursion uses).

For Videos Join Our Youtube Channel: Join Now