Leetcode 885. Spiral Matrix III解题报告(python)

885. Spiral Matrix III

  1. Spiral Matrix III python solution

题目描述

On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.
Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column.
Now, we walk in a clockwise spiral shape to visit every position in this grid.
Whenever we would move outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.)
Eventually, we reach all R * C spaces of the grid.
Return a list of coordinates representing the positions of the grid in the order they were visited.

Leetcode 885. Spiral Matrix III解题报告(python)_第1张图片

解析

解题思路也比较简单,只需要顺时针行走,检查目前的位置是否在grid内,如果在范围内就存下。

// An highlighted block
class Solution:
    def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
        totalItems = R*C
        step = 0
        x,y = r0, c0
        res = [[x, y]]
        while len(res)<R*C:
            step += 1
            x, y, res = self.moveRight(x, y, step, res, R, C)
            x, y, res = self.moveDown(x,y, step, res, R, C)
            step += 1
            x, y, res = self.moveLeft(x, y, step, res, R, C)
            x, y, res = self.moveUp(x, y, step, res, R, C)
        
        return res
    
    def moveRight(self, x, y, step, res, R, C):
        while step > 0:
            step -= 1
            y += 1
            if 0<=x<R and 0<=y<C:
                res.append([x,y])
        
        return x, y, res
        
    def moveDown(self, x, y, step, res, R, C):
        while step > 0:
            step -= 1
            x += 1
            if 0<=x<R and 0<=y<C:
                res.append([x,y])

        return x, y, res
    
    def moveLeft(self, x, y, step, res, R, C):
        while step > 0:
            step -= 1
            y -= 1
            if 0<=x<R and 0<=y<C:
                res.append([x,y])
        

Reference

https://leetcode.com/problems/spiral-matrix-iii/discuss/411199/Python-Solution-very-clean

你可能感兴趣的:(LeetCode)