Skip to content

Commit 1b952dc

Browse files
authored
Create matrix-cells-in-distance-order.py
1 parent b486391 commit 1b952dc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Time: O(m * n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def allCellsDistOrder(self, R, C, r0, c0):
6+
"""
7+
:type R: int
8+
:type C: int
9+
:type r0: int
10+
:type c0: int
11+
:rtype: List[List[int]]
12+
"""
13+
def append(R, C, r, c, result):
14+
if 0 <= r < R and 0 <= c < C:
15+
result.append([r, c])
16+
17+
result = [[r0, c0]]
18+
for d in xrange(1, R+C):
19+
append(R, C, r0-d, c0, result)
20+
for x in xrange(-d+1, d):
21+
append(R, C, r0+x, c0+abs(x)-d, result)
22+
append(R, C, r0+x, c0+d-abs(x), result)
23+
append(R, C, r0+d, c0, result)
24+
return result

0 commit comments

Comments
 (0)