Leetcode 54. Spiral Matrix

题目描述:按照螺旋顺序打印矩阵。

题目链接:Leetcode 54. Spiral Matrix

思考思路:就是矩阵的一个搜索遍历,用到思想就是要dx\dy 来控制方向,正如 (0,0,-1,1)这样的方向选择,就是选择不同方向,要思考的就是什么时候转变方向。

代码如下

class Solution(object):
    def spiralOrder(self, matrix):
        
        m=len(matrix)
        if not m:
            return []
        n=len(matrix[0])
        
        x,y,dx,dy=0,0,0,1
        ans=[]
        for k in range(m*n):
            ans.append(matrix[x][y])
            matrix[x][y]=0  #填充0
            if matrix[(x+dx)%m][(y+dy)%n]==0:  #越界0
                dx, dy = dy , -dx
            x += dx
            y += dy
        return ans

class Solution(object):
    def spiralOrder(self, matrix):
        if not matrix: return []
        rows, cols, result = len(matrix), len(matrix[0]), []
        N, x, y, dx, dy = rows * cols, -1, 0, 1, 0
        while True:
            for i in range(cols):
                x, y = x + dx, y + dy
                result += matrix[y][x],
            rows -= 1
            if not rows: return result
            dx, dy = -dy, dx
            for i in range(rows):
                x, y = x + dx, y + dy
                result += matrix[y][x],
            cols -= 1
            if not cols: return result
            dx, dy = -dy, dx  #这个利用增量来做
class Solution:
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        ans = []
        if not matrix or not matrix[0]:
            return []
        tr = 0
        tc = 0
        dr = len(matrix) - 1
        dc = len(matrix[0]) - 1
        while(tr<=dr and tc<=dc):
            self.getAns(matrix,tr,tc,dr,dc,ans)
            tr += 1
            tc += 1
            dr -= 1
            dc -= 1
        return ans
        
    def getAns(self,matrix,tr,tc,dr,dc,ans):
        if(tc==dc):
            for i in range(tr,dr+1):
                ans.append(matrix[i][dc])
        elif (tr==dr):
            for i in range(tc,dc+1):
                ans.append(matrix[tr][i])
        else:
            curC = tc
            curR = tr
            while(curC != dc):
                ans.append(matrix[tr][curC])
                curC += 1
            while(curR!=dr):
                ans.append(matrix[curR][dc])
                curR += 1
            while(curC != tc):
                ans.append(matrix[dr][curC])
                curC -= 1
            while(curR != tr):
                ans.append(matrix[curR][curC])
                curR -= 1   

参考链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值