Skip to content

Commit e4873ff

Browse files
authored
Create spiral-matrix-iv.py
1 parent b7f5181 commit e4873ff

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Python/spiral-matrix-iv.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Time: O(m * n)
2+
# Space: O(1)
3+
4+
# Definition for singly-linked list.
5+
class ListNode(object):
6+
def __init__(self, val=0, next=None):
7+
pass
8+
9+
10+
# linked list, array
11+
class Solution(object):
12+
def spiralMatrix(self, m, n, head):
13+
"""
14+
:type m: int
15+
:type n: int
16+
:type head: Optional[ListNode]
17+
:rtype: List[List[int]]
18+
"""
19+
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
20+
result = [[-1]*n for _ in xrange(m)]
21+
i = j = d = 0
22+
while head:
23+
result[i][j] = head.val
24+
if not (0 <= i+directions[d][0] < m and 0 <= j+directions[d][1] < n and result[i+directions[d][0]][j+directions[d][1]] == -1):
25+
d = (d+1)%4
26+
i, j = i+directions[d][0], j+directions[d][1]
27+
head = head.next
28+
return result

0 commit comments

Comments
 (0)