题解 | #螺旋矩阵#

螺旋矩阵

http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

模拟遍历过程,注意边界条件

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param matrix int整型二维数组 
# @return int整型一维数组
#
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        # write code here
        if not matrix: return []
        i = j = 0
        ans = []
        while 1:
            if matrix[i][j] == 101:
                break
            while i >= 0 and j >= 0 and i < len(matrix) and j < len(matrix[0]) and matrix[i][j] != 101:
                ans.append(matrix[i][j])
                matrix[i][j] = 101
                if j + 1 < len(matrix[0]) and matrix[i][j+1] != 101:
                    j = j+1
                else: break
            i = i+1
            while i >= 0 and j >= 0 and i < len(matrix) and j < len(matrix[0]) and matrix[i][j] != 101:
                ans.append(matrix[i][j])
                matrix[i][j] = 101
                if i + 1 < len(matrix) and matrix[i+1][j] != 101:
                    i = i+1
                else: break
            j = j-1
            while i >= 0 and j >= 0 and i < len(matrix) and j < len(matrix[0]) and matrix[i][j] != 101:
                ans.append(matrix[i][j])
                matrix[i][j] = 101
                if j - 1 >=0 and matrix[i][j-1] != 101:
                    j = j-1
                else: break
            i = i-1
            while i >= 0 and j >= 0 and i < len(matrix) and j < len(matrix[0]) and matrix[i][j] != 101:
                ans.append(matrix[i][j])
                matrix[i][j] = 101
                if i - 1 >=0 and matrix[i-1][j] != 101:
                    i = i-1
                else: break
            j = j+1
        return ans
            
            
            
            
            
            
            
            
            
            
            
            
            
            
        
全部评论

相关推荐

04-08 16:35
门头沟学院 Java
站队站对牛:实在是恶心的公司
点赞 评论 收藏
分享
饼子吃到撑:学院本是这样的,找工作拼运气,你技术再好人家筛选学历照样沉入海底,海投就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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