//顺序依次为左上右下,一开始向右,因此d=1, 列+1 int dx[4] = {-1 , 0 , 1 , 0}, dy[4] = {0 , 1 , 0 , -1}; //注意这里循环是以填的数cnt:1~n*n来循环n^2次 for(int cnt = 1 , x = 0 , y = 0 , d = 1 ;cnt <= n * n ; cnt++){ res[x][y] = cnt; int a = x + dx[d] , b = y + dy[d]; if(a < 0 || a >= n || b < 0 || b >= n || res[a][b]){ d = (d + 1) % 4; a = x + dx[d] , b = y + dy[d]; } x = a , y = b; }
classSolution { public: vector<int> spiralArray(vector<vector<int>>& array) { if (array.empty()) return {}; int l = 0, r = array[0].size() - 1, t = 0, b = array.size() - 1; vector<int> res; while(true) { for (int i = l; i <= r; i++) res.push_back(array[t][i]); // left to right if (++t > b) break; for (int i = t; i <= b; i++) res.push_back(array[i][r]); // top to bottom if (l > --r) break; for (int i = r; i >= l; i--) res.push_back(array[b][i]); // right to left if (t > --b) break; for (int i = b; i >= t; i--) res.push_back(array[i][l]); // bottom to top if (++l > r) break; } return res; } };
int r = array.size(),c = array[0].size(); vector<vector<bool>> visited(r , vector<bool>(c)); int t = r * c;
vector<int> res(t); int dx[] = {-1 , 0 , 1, 0}, dy[] = {0 , 1 , 0, -1}; for(int i =0 ,a = 0 , b = 0 , d = 1; i < t ; i++ ){ res[i] = array[a][b]; visited[a][b] = true; int na = a + dx[d] , nb = b + dy[d]; if(na< 0 || na >= r || nb < 0 || nb >= c || visited[na][nb]){ d = (d + 1) % 4; na = a + dx[d] , nb = b + dy[d]; } a = na , b = nb; } return res; } };