8/13/2019 Spiral Primes Problem 58
Given a 2D array, print it in spiral form. See the following examples.
Examples:
Spiral primes. Published on Friday, 5th December 2003, 06:00 pm; Solved by 35497; Difficulty rating: 5%. Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30.
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
Approach: The above problem can be solved using four for loops which prints all the elements. Every for loop defines a single direction movement along with the matrix. The first for loop represents the movement from left to right, whereas the second crawl represents the movement from top to bottom, the third represents the movement from the right to left, and the fourth represents the movement from bottom to up. The four variable along with their use is given below.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Time Complexity: Time complexity of the above solution is O(mn).
Recursive Approach:
The above problem can be solved by printing the boundary of the Matrix recursively. In each recursive call, we decrease the dimensions of the matrix.
Below is the C++ implementation for the same:
C++
Please write comments if you find the above code incorrect, or find other ways to solve the same problem.
Recommended Posts:Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |