Leetcode 54 Spiral Matrix

HowieLee59發表於2018-12-13

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]

這個題為簡單的模擬,但是不同的模擬方式時間複雜度為不同,主要方法為標記四個指標,分別進行運動。

1)

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if(matrix.empty()) return res;
        int n = matrix.size(),m = matrix[0].size();
        vector<vector<bool>> st(n,vector<bool>(m,false));//定義一個二維的List
        int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};//定義運動不同的方向所產生的位移
        int x = 0,y = 0,d = 1;
        for(int k = 0 ; k < n * m ; k++){
            res.push_back(matrix[x][y]);
            st[x][y] = true;//標記true或者是false
            
            int a = x + dx[d],b = y + dy[d];//標記x和y的位置
            if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]){
                d = (d + 1) % 4;//順時針方向發生轉換的時候
                a = x + dx[d], b = y + dy[d];//標記x和y的位置 
            }
            x = a,y = b;
        }
        return res;
    }
};

2)


class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
       if(matrix.empty())
          return vector<int>();
        int m = matrix[0].size();
        int n = matrix.size();
         
        vector<int> res;
 
        int roundTime= (min(n,m)+1)/2;
        for (int i = 0;i<roundTime ;i++){
            for (int j = i;j<=m-i-1;j++) res.push_back(matrix[i][j]);
            for (int j = i+1;j<=n-i-1;j++) res.push_back(matrix[j][m-i-1]);
            if(i<n-i-1) {for (int j = m-i-2;j>i;j--) res.push_back(matrix[n-i-1][j]);}
            if(i<m-i-1) {for (int j = n-i-1;j>i;j--) res.push_back(matrix[j][i]);}
        }
        return res;
    }
};

相關文章