Print the matrix clockwise

Enter a matrix and print out each number in clockwise order from the outside in.

Example 1:

Input: matrix = [[1, 2, 3], [4 and 6], [7,8,9]] output:,2,3,6,9,8,7,4,5 [1] example 2:

Input: matrix = [[1, 2, 3, 4], [5,6,7,8], [9,10,11,12]] output:,2,3,4,8,12,11,10,9,5,6,7 [1]

Limitations:

0 <= matrix.length <= 100

0 <= matrix[i].length <= 100

Answer:

java

class Solution {
    public int[] spiralOrder(int[][] matrix) {
            
        if(matrix.length == 0) return new int[0];
        int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0;
        int[] res = new int[(r + 1) * (b + 1)];
        while(true) {
            for(int i = l; i <= r; i++) res[x++] = matrix[t][i]; // left to right.
            if(++t > b) break;
            for(int i = t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom.
            if(l > --r) break;
            for(int i = r; i >= l; i--) res[x++] = matrix[b][i]; // right to left.
            if(t > --b) break;
            for(int i = b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top.
            if(++l > r) break;
        }
        returnres; }}Copy the code

python

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int] "" "if  not matrix :
            return []
        res = []
        l = 0
        r = len(matrix[0]) - 1
        top = 0
        low = len(matrix) - 1

        while True:
            for i in range(l,r+1):
                res.append(matrix[top][i])
           
            top = top + 1
            if top>low:break
            for j in range(top,low+1):
                res.append(matrix[j][r])
            
            r = r - 1
            if r<l:break
            for m in range(r,l- 1.- 1):
                res.append(matrix[low][m])
            
            low = low - 1
            if low<top:break
            for n in range(low,top- 1.- 1):
                res.append(matrix[n][l])
            l = l + 1
            if l>r:
                break
        return res
Copy the code