# Spiral Matrix II in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a positive integer n, we have to generate a square matrix with n2 elements in spiral order. So if n = 5, then the matrix will be −

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

Let us see the steps −

• set (row1, col1) := (0, 0) and (row2, col2) := (n, n), and create one matrix called res, then fill it with 0s, and set num := 1
• while num <= n2,
• for i in range col1 to col2,
• res[row1, i] = num, incase num by 1
• if num > n2, then break
• for i in range row1 + 1 to row2,
• res[i, col2-1] = num, incase num by 1
• if num > n2, then break
• for i in range col2 – 2 down to col1 – 1,
• res[row2 – 1, i] = num, incase num by 1
• if num > n2, then break
• for i in range row2 – 2 down to row1,
• res[i, col1] = num, incase num by 1
• increase row1 by 1, decrease row2 by 1, increase col1 by 1 and decrease col2 by 1
• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution(object):
def generateMatrix(self, n):
row1 = 0
col1 = 0
row2 = n
col2 = n
result = [ [0 for i in range(n)] for j in range(n)]
num = 1
while num<=n**2:
for i in range(col1,col2):
result[row1][i] = num
num+=1
if num > n**2:
break
for i in range(row1+1,row2):
result[i][col2-1] = num
num+=1
if num > n**2:
break
for i in range(col2-2,col1-1,-1):
result[row2-1][i] = num
num+=1
if num > n**2:
break
for i in range(row2-2,row1,-1):
result[i][col1] = num
num+=1
row1+=1
row2-=1
col1+=1
col2-=1
#print(result)
return result
ob1 = Solution()
print(ob1.generateMatrix(4))

## Input

4

## Output

[[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
Updated on 04-May-2020 05:56:58