To prove safety offer - traverse the matrix from outside to inside

Title Description

Enter a matrix, in order from outside to inside in a clockwise order to print out sequentially for each number, for example, if you enter the following 4 X 4 matrix: 1,234,567,891,011,121,314 15 sequentially printed out 16 digital 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. 

Input n * m matrix, and returns a list

Ideas:

Want to start with a recursive, recursion can not solve the problem and found that the length of matrix ranks do not want to like. There appears out of range.

Then read other people's answers, with the two pairs of hands!

up, down, left, right when there is any pair of pointers meet, and it shows that this two-dimensional matrix traversal over

class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        if len(matrix)==0:
            return []
        
        ans = []
        h = len(matrix)
        r = len(matrix[0])
        left = 0
        right = r-1
        down = h-1
        up = 0
        while True:
            
            for j in range(left,right+1):
                ans.append(matrix[up][j])
            up += 1
            if up > down:
                break
            for i in range(up,down+1):
                ans.append(matrix[i][right])
            right-=1
            if left > right:
                break
            for j in range(left,right+1):
                ans.append(matrix[down][right+left-j])
            down -= 1
            if up > down:
                break
            for i in range(up,down+1):
                ans.append(matrix[down+up-i][left])
            left+=1
            if right < left:
                break
        return ans

 

Published 82 original articles · won praise 2 · Views 4368

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104744993