//给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
//
//
//
// 示例 1:
//
//
//输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
//输出:[1,2,3,6,9,8,7,4,5]
//
//
// 示例 2:
//
//
//输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
//输出:[1,2,3,4,8,12,11,10,9,5,6,7]
//
//
//
//
// 提示:
//
//
// m == matrix.length
// n == matrix[i].length
// 1 <= m, n <= 10
// -100 <= matrix[i][j] <= 100
//
// Related Topics 数组
// 👍 620 👎 0
/*
* 54 螺旋矩阵
* 2021-03-01 14:33:36
* @author oxygenbytes
*/
#include "leetcode.h"
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty() || matrix[0].empty()) return {};
int m = matrix.size();
int n = matrix[0].size();
vector<int> ans;
int d = 1;
int i = 0, j = 0;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
for(int k = 0;k < m * n;k++){
ans.push_back(matrix[i][j]);
matrix[i][j] = 0;
int a = i + dx[d];
int b = j + dy[d];
if(a < 0 || a >= m || b < 0 || b >= n || matrix[a][b] == 0){
d = (d + 1) % 4;
a = i + dx[d];
b = j + dy[d];
}
i = a, j = b;
}
return ans;
}
};
//leetcode submit region end(Prohibit modification and deletion)