Swordfinger offer: Print the matrix clockwise

Posted by fractalvibes on Thu, 07 Nov 2019 21:53:37 +0100

Title Description
Enter a matrix to print out each number in clockwise order from outside to inside. For example, if you enter the following 4 X 4 matrix: 1 2 3 4 5 6 7 9 11 12 13 14 15 16, the numbers 1,2,3,4,8,12,16,14,13,9,5,7,11,10 will be printed out sequentially.

By printing in one direction, we can print the entire matrix from outside to inside in a loop.In this topic, we can select a starting point (upper left corner) at a time and print a circle clockwise.

class Solution:
    # Matx type is a two-dimensional list, need to return list
    def printMatrix(self, matrix):
        def helper(start_row, start_col):
            # When printing a circle, the right direction must be printed.
            # The other three directions need to meet a certain condition before printing
            end_row = rows - start_row - 1
            end_col = cols - start_col - 1
            for i in range(start_col, end_col + 1):
                ans.append(matrix[start_row][i])

            if end_row > start_row:  # Only go down if the number of rows is greater than 2
                for i in range(start_row + 1, end_row + 1):
                    ans.append(matrix[i][end_col])

            # Left only if the number of columns is greater than 2 and the number of rows is greater than 2.If the number of lines is 1, the same line will be printed repeatedly
            if end_col > start_col and end_row > start_row:
                for i in range(end_col - 1, start_col - 1, -1):
                    ans.append(matrix[end_row][i])

            # Only go up if the number of rows is greater than _3_ [and the number of columns is greater than 2].
            # If the number of lines is 2, all prints are finished after going left
            if end_row > start_row + 1 and end_col > start_col:
                for i in range(end_row - 1, start_row, -1):
                    ans.append(matrix[i][start_col])

        if not isinstance(matrix, list) or not isinstance(matrix[0], list):
            return
        rows, cols = len(matrix), len(matrix[0])
        ans = []
        start = 0
        # Determine if this circle needs to be printed.From observation and summary, we know that when rows and cols are both larger than the starting coordinates, they need to be printed
        while start * 2 < min(rows, cols):
            helper(start, start)
            start += 1

        return ans

Topics: Python