Skip to content

Commit 3af5708

Browse files
python: add problem 54 and unit test
1 parent c5d7881 commit 3af5708

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

Python/solution_51_60.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# -*- coding: UTF-8 -*-
2+
3+
class Solution_51_60:
4+
def spiralOrder(self, matrix):
5+
"""
6+
problem 54 - Spiral Matrix
7+
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
8+
9+
For example,
10+
Given the following matrix:
11+
12+
[
13+
[ 1, 2, 3 ],
14+
[ 4, 5, 6 ],
15+
[ 7, 8, 9 ]
16+
]
17+
You should return [1,2,3,6,9,8,7,4,5].
18+
:type matrix: List[List[int]]
19+
:rtype: List[int]
20+
"""
21+
22+
res = []
23+
24+
if len(matrix) == 0:
25+
return res
26+
if len(matrix[0]) == 0:
27+
return res
28+
29+
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
30+
x, y = 0, -1
31+
step = [len(matrix[0]), len(matrix) - 1]
32+
curr_direction = 0
33+
34+
while step[curr_direction % 2] != 0:
35+
for i in range(step[curr_direction % 2]):
36+
x += direction[curr_direction][0]
37+
y += direction[curr_direction][1]
38+
res.append(matrix[x][y])
39+
40+
step[curr_direction % 2] -= 1
41+
curr_direction = (curr_direction + 1) % 4
42+
43+
return res

Python/test_solution_51_60.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from unittest import TestCase
2+
from solution_51_60 import Solution_51_60
3+
4+
# -*- coding: UTF-8 -*-
5+
class TestSolution_51_60(TestCase):
6+
def setUp(self):
7+
self.sln = Solution_51_60()
8+
9+
def test_spiralOrder(self):
10+
m = [[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ]]
11+
res = [1,2,3,6,9,8,7,4,5]
12+
self.assertEqual(self.sln.spiralOrder(m),res)
13+
self.assertEqual(self.sln.spiralOrder([[1]]), [1])

0 commit comments

Comments
 (0)