太久没有编码了,逻辑思维跟不上节奏,阅读别人的代码也费了老半天的劲儿。题目原文在这里。
简要概括题目要求就是输出从方形矩阵中任意位置出发,螺旋遍历矩阵位置并按顺序输出。下面是别人的Python代码:
class Solution(object):
def spiralMatrixIII(self, R, C, r0, c0):
ans = [(r0, c0)]
if R * C == 1: return ans
# For walk length k = 1, 3, 5 ...
for k in xrange(1, 2*(R+C), 2):
# For direction (dr, dc) = east, south, west, north;
# and walk length dk...
for dr, dc, dk in ((0, 1, k), (1, 0, k), (0, -1, k+1), (-1, 0, k+1)):
# For each of dk units in the current direction ...
for _ in xrange(dk):
# Step in that direction
r0 += dr
c0 += dc
# If on the grid ...