8000 54, x-axis left to right, y-axis top to bottom, dx, dy = -dy, dx turn… · chaor/LeetCode_Python_Accepted@39bf0b9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 39bf0b9

Browse files
committed
54, x-axis left to right, y-axis top to bottom, dx, dy = -dy, dx turns right
1 parent 853627d commit 39bf0b9

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

54_Spiral_Matrix.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,23 @@
1-
# 2015-08-30 Runtime: 44 ms
2-
class Solution:
3-
# @param {integer[][]} matrix
4-
# @return {integer[]}
1+
# 2016-03-18 22 tests, 44 ms
2+
class Solution(object):
53
def spiralOrder(self, matrix):
4+
"""
5+
:type matrix: List[List[int]]
6+
:rtype: List[int]
7+
"""
68
if not matrix: return []
7-
i, j, di, dj, M, N, res = 0, 0, 0, 1, len(matrix), len(matrix[0]), []
9+
rows, cols, result = len(matrix), len(matrix[0]), []
10+
N, x, y, dx, dy = rows * cols, -1, 0, 1, 0
811
while True:
9-
res.append(matrix[i][j])
10-
if len(res) == M * N: return res
11-
matrix[i][j] = None
12-
if matrix[(i + di) % M][(j + dj) % N] is None:
13-
di, dj = dj, -di # turn right
14-
i, j = i + di, j + dj
12+
for i in xrange(cols):
13+
x, y = x + dx, y + dy
14+
result += matrix[y][x],
15+
rows -= 1
16+
if not rows: return result
17+
dx, dy = -dy, dx
18+
for i in xrange(rows):
19+
x, y = x + dx, y + dy
20+
result += matrix[y][x],
21+
cols -= 1
22+
if not cols: return result
23+
dx, dy = -dy, dx

0 commit comments

Comments
 (0)
0