Skip to content

Commit f8a9329

Browse files
Merge pull request Py-Contributors#476 from SOURAB-BAPPA/spiralmatrix
Spiralmatrix
2 parents 2eebda3 + 14e5145 commit f8a9329

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

Python/Algorithms/README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ List of Algorithms in Python contained in this repository
1212
- [Recursion Algorithms](#recursionalgorithms)
1313
- [Searching Algorithms](#searchingalgorithms)
1414
- [Sorting Algorithms](#sortingalgorithms)
15-
15+
- [Spiral Matrix](#SpiralMatrix)
1616
### Backtracking Algorithms:
1717
Backtracking is a technique for solving problems recursively by trying to build a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point of time.
1818
Example of implementation- Soduku solving.
@@ -52,3 +52,6 @@ Examples of implementation- Binary Search, Linear Search, Fibonacci Search.
5252
### Sorting Algorithms:
5353
A Sorting algorithm is an algorithm that puts elements of a list in a certain order. The most frequently used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the efficiency of other algorithms that require input data to be in sorted lists.
5454
Examples of implementation- Quick Sort, Merge Sort.
55+
56+
### Spiral Matrix:
57+
The Spiral Matrix problem takes a 2-Dimensional array of N-rows and M-columns as an input, and prints the elements of this matrix in spiral order. The spiral begins at the top left corner of the input matrix, and prints the elements it encounters, while looping towards the center of this matrix, in a clockwise manner.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
def spiral_matrix():
2+
i = 0 # starting row index
3+
j = 0 # starting column index
4+
c = 0
5+
print("Please enter number of rows of the spiral matrix:")
6+
try:
7+
no = int(input())
8+
except Exception:
9+
print("Please enter numbers only")
10+
return 0
11+
high = no ** 2
12+
val = 1
13+
a = [[0 for i in range(no)] for j in range(no)]
14+
15+
while val <= high:
16+
while j < no - 1: # for first row
17+
a[i][j] = val
18+
val += 1
19+
j += 1
20+
while i < no - 1: # for last column
21+
a[i][j] = val
22+
val += 1
23+
i += 1
24+
while j > c: # for last row
25+
a[i][j] = val
26+
val += 1
27+
j -= 1
28+
while i > c: # for first column
29+
a[i][j] = val
30+
val += 1
31+
i -= 1
32+
no -= 1
33+
i += 1
34+
j += 1
35+
c += 1
36+
if val == high: # for odd matrix size
37+
a[i][j] = val
38+
break
39+
print("Spiral matrix is:")
40+
for row in a:
41+
print(row)
42+
43+
44+
spiral_matrix()

0 commit comments

Comments
 (0)