|
| 1 | +// class Solution { |
| 2 | +// public: |
| 3 | +// vector<int> spiralOrder(vector<vector<int>>& matrix) { |
| 4 | +// int n = matrix.size(), m = matrix[0].size(); |
| 5 | +// vector<int> sorted; |
| 6 | +// vector<vector<bool>> check(n, vector<bool>(m, false)); |
| 7 | +// queue<pair<int, pair<int, int>>> que; |
| 8 | + |
| 9 | +// int dx[4] = {-1, 0, 1, 0}; |
| 10 | +// int dy[4] = {0, 1, 0, -1}; |
| 11 | +// // 0: up, 1: right, 2: down, 3: left |
| 12 | +// que.push({1, {0, 0}}); |
| 13 | +// sorted.push_back(matrix[0][0]); |
| 14 | +// check[0][0] = true; |
| 15 | +// while(!que.empty()) { |
| 16 | +// int d = que.front().first; |
| 17 | +// int x = que.front().second.first; |
| 18 | +// int y = que.front().second.second; |
| 19 | +// que.pop(); |
| 20 | + |
| 21 | +// int new_x = x + dx[d]; |
| 22 | +// int new_y = y + dy[d]; |
| 23 | +// if(new_x >= 0 && new_y >= 0 && new_x < n && new_y < m && check[new_x][new_y] == false) { |
| 24 | +// check[new_x][new_y] = true; |
| 25 | +// sorted.push_back(matrix[new_x][new_y]); |
| 26 | +// que.push({d, {new_x, new_y}}); |
| 27 | +// continue; |
| 28 | +// } |
| 29 | +// d = (d + 1) % 4; |
| 30 | +// new_x = x + dx[d]; |
| 31 | +// new_y = y + dy[d]; |
| 32 | +// if(new_x >= 0 && new_y >= 0 && new_x < n && new_y < m && check[new_x][new_y] == false) { |
| 33 | +// check[new_x][new_y] = true; |
| 34 | +// sorted.push_back(matrix[new_x][new_y]); |
| 35 | +// que.push({d, {new_x, new_y}}); |
| 36 | +// } |
| 37 | +// } |
| 38 | + |
| 39 | +// return sorted; |
| 40 | +// } |
| 41 | +// }; |
| 42 | + |
| 43 | +class Solution { |
| 44 | +public: |
| 45 | + vector<int> spiralOrder(vector<vector<int>>& matrix) { |
| 46 | + int n = matrix.size(), m = matrix[0].size(); |
| 47 | + int top = 0, down = n - 1, left = 0, right = m - 1; |
| 48 | + vector<int> sorted; |
| 49 | + while(top <= down && left <= right) { |
| 50 | + for(int i = left; i <= right; i++) |
| 51 | + sorted.push_back(matrix[top][i]); |
| 52 | + top++; |
| 53 | + |
| 54 | + for(int i = top; i <= down; i++) |
| 55 | + sorted.push_back(matrix[i][right]); |
| 56 | + right--; |
| 57 | + |
| 58 | + if(top <= down) { |
| 59 | + for(int i = right; i >= left; i--) |
| 60 | + sorted.push_back(matrix[down][i]); |
| 61 | + down--; |
| 62 | + } |
| 63 | + |
| 64 | + if(left <= right) { |
| 65 | + for(int i = down; i >= top; i--) |
| 66 | + sorted.push_back(matrix[i][left]); |
| 67 | + left++; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return sorted; |
| 72 | + } |
| 73 | +}; |
| 74 | + |
0 commit comments