LeetCode54.螺旋矩阵
题解思路
代码
class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {vector<int> res;int n = matrix.size();// 行int m = matrix[0].size(); // 列vector<vector<bool>> st(n, vector<bool>(m));// 方向数组int dx[] = {0, 1, 0, -1};int dy[] = {1, 0, -1, 0};for(int i = 0, x = 0, y = 0, d = 0; i < n * m; i++){res.push_back(matrix[x][y]);st[x][y] = true;// 按照要求遍历四个方向int x1 = x + dx[d], y1 = y + dy[d];// 边界判断if(x1 < 0 || x1 >= n || y1 < 0 || y1 >= m || st[x1][y1]){// 遇到边界,就改变方向d = (d + 1) % 4;x1 = x + dx[d], y1 = y + dy[d];}x = x1, y = y1;}return res;}
};