剑指 顺时针输出

顺时针打印矩阵

http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a

设立一个directions数组,存储方向,然后在满足条件的时候,转换方向,请注意当row或col到达边界的时候,或者当前遍历值已经“输出”过的时候,则转换方向。

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        directions=[(0,1),(1,0),(0,-1),(-1,0)]
        row= len(matrix)
        col=len(matrix[0])
        result=[0]*(row*col)
        count=0
        r=c=0
        index=0
        dx=dy=0
        if row*col==0:
            return []
        while count <=row*col-1:

            result[count]=matrix[r][c]
            matrix[r][c]=-1
            count+=1
            dx=directions[index][0]
            dy=directions[index][1]

            if r+dx==row or c+dy==col or matrix[r+dx][c+dy]==-1:
                index=(index+1)%4
            dx=directions[index][0]
            dy=directions[index][1]

            r+=dx
            c+=dy
        return result

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务