54. Spiral Matrix(剑指offer--19)

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

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





class Solution:
    def __init__(self):
        self.res = []
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        
        def backtrack(matrix,l,r,u,d):
            if l>r or u>d:
                return 
            
            for i in range(l,r+1):
                self.res.append(matrix[u][i])
            for i in range(u+1,d+1):
                self.res.append(matrix[i][r])
            
            if u!=d:
                for i in range(l,r)[::-1]:
                    self.res.append(matrix[d][i])   
            if l!=r:
                for i in range(u+1,d)[::-1]:
                    self.res.append(matrix[i][l])

            backtrack(matrix,l+1,r-1,u+1,d-1)
        
        n1 = len(matrix)
        n2 = len(matrix[0])

        backtrack(matrix,0,n2-1,0,n1-1)
        return self.res

        

 








class Solution {
public:
    vector<int> ret;
    void cricle(vector<vector<int>>& matrix,int m1,int m2,int n1,int n2) {
        //[m1,m2)   
        //cout << m1 << " " << m2 << " " << n1 << " " << n2 << endl;     
        // 只有一行
        if (m2-m1==1) {
            for(int j = n1; j < n2;j++) {
                ret.push_back(matrix[m1][j]);
            }
            return;
        }
        //只有一列
        if (n2-n1==1) {
            for(int i = m1; i < m2;i++) {
                ret.push_back(matrix[i][n1]);
            }
            return;
        }

        if(m1>=m2||n1>=n2)return ;
        
        for(int j=n1;j<n2-1;j++){
            ret.push_back(matrix[m1][j]) ;
        }
        
        for(int i=m1;i<m2-1;i++){
            ret.push_back(matrix[i][n2-1]) ;
        }
    
        for(int j=n2-1;j>n1;j--){
            ret.push_back(matrix[m2-1][j]) ;
            cout << matrix[m2-1][j] << endl;
        }
        for(int i=m2-1;i>m1;i--){
            ret.push_back(matrix[i][n1]) ;
        }
        
        cricle(matrix,m1+1,m2-1,n1+1,n2-1);
    }
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size() ;
        if(m==0)return ret ;
        int n = matrix[0].size() ;
        cricle(matrix,0,m,0,n) ;
        return ret ;
    }   
};

 

 

 

19顺时针打印矩阵

 

 

posted @ 2018-06-15 22:41  乐乐章  阅读(163)  评论(0编辑  收藏  举报