Skip to content

Commit 0b1a845

Browse files
committed
Adding Efficient Solution for Problem - 54 - Spiral Matrix
1 parent 5ad402d commit 0b1a845

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Spiral_Matrix/EfficientSolution.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 54
6+
## Problem Name: Spiral Matrix
7+
##===================================
8+
#
9+
#Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
10+
#
11+
#Example 1:
12+
#
13+
#Input:
14+
#[
15+
# [ 1, 2, 3 ],
16+
# [ 4, 5, 6 ],
17+
# [ 7, 8, 9 ]
18+
#]
19+
#Output: [1,2,3,6,9,8,7,4,5]
20+
#
21+
#Example 2:
22+
#
23+
#Input:
24+
#[
25+
# [1, 2, 3, 4],
26+
# [5, 6, 7, 8],
27+
# [9,10,11,12]
28+
#]
29+
#Output: [1,2,3,4,8,12,11,10,9,5,6,7]
30+
class Solution:
31+
def spiralOrder(self, matrix):
32+
if not matrix: #Condition-check: If matrix is empty
33+
return [] #Return empty array
34+
tmp = [] #Initialize tmp empty list
35+
r_b, r_e, c_b, c_e = 0, len(matrix), 0, len(matrix[0]) #Initialize row_begin, row_end, column_begin, column_end
36+
while r_e > r_b and c_e > c_b: #Loop while the condition meets
37+
for i in range(c_b, c_e): #Loop through c_b to c_e
38+
tmp.append(matrix[r_b][i]) #Append the given value in list
39+
for i in range(r_b + 1, r_e - 1): #Loop through the given start and end point
40+
tmp.append(matrix[i][c_e - 1]) #Append the given value in list
41+
if r_e != r_b + 1: #Condition-check: If r_e's value is not equal to r_b + 1
42+
for j in range(c_e - 1, c_b -1, -1): #Loop through the given start and end point by decreasing j by 1
43+
tmp.append(matrix[r_e - 1][j] #Append the given value in list
44+
if c_b != c_e - 1: #Condition-check: If c_b's value is not equal to c_e - 1
45+
for j in range(r_e - 2, r_b, -1): #Loop through the given start and end point by decreasing j by 1
46+
tmp.append(matrix[j][c_b]) #Append the given value in list
47+
r_b, r_e, c_b, c_e = r_b + 1, r_e - 1, c_b + 1, c_e - 1 #Update the values
48+
return tmp #Return tmp list at the end

0 commit comments

Comments
 (0)