#define ifOK(x, y) if (x >= 0 && x < matrix.size() && y >= 0 && y < matrix[0].size() && matrix[x][y] != ALREADY) // 判断(x, y)是否OK(既在数据范围内又没被遍历过) int nx = x + directions[nowDirection][0]; int ny = y + directions[nowDirection][1]; ifOK(nx, ny) { ... }
如果下一个元素可行就更新$x$和$y$为当前方向的下一个元素;
如果下一个元素不可行就更改遍历方向为下一个方向,并更新$x$和$y$为新方向的下一个元素。
1 2 3
nowDirection = (nowDirection + 1) % 4; x += directions[nowDirection][0]; y += directions[nowDirection][1];
#define ALREADY 101 #define ifOK(x, y) if (x >= 0 && x < matrix.size() && y >= 0 && y < matrix[0].size() && matrix[x][y] != ALREADY) constint directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 👉👇👈👆
classSolution { public: vector<int> spiralOrder(vector<vector<int>>& matrix){ int n = matrix.size() * matrix[0].size(); vector<int> ans(n); int nowDirection = 0; // 现在的方向 int loc = 0; // 遍历了几个元素了 int x = 0, y = 0; // 当前应该遍历的位置 while (loc < n) { ans[loc++] = matrix[x][y]; matrix[x][y] = ALREADY; int nx = x + directions[nowDirection][0]; int ny = y + directions[nowDirection][1]; ifOK(nx, ny) { x = nx, y = ny; } else { nowDirection = (nowDirection + 1) % 4; x += directions[nowDirection][0]; y += directions[nowDirection][1]; } } return ans; } };