1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { if (matrix.size() == 0 || matrix[0].size() == 0) return {};
int rows = matrix.size(), cols = matrix[0].size(); int left = 0, right = cols - 1, top = 0, bottom = rows - 1; vector<int> res; res.reserve(rows * cols); while (left <= right && top <= bottom) { for (int col = left; col <= right; col ++) { res.push_back(matrix[top][col]); } for (int row = top + 1; row <= bottom; row ++) { res.push_back(matrix[row][right]); } if (left < right && top < bottom) { for (int col = right - 1; col > left; col --) { res.push_back(matrix[bottom][col]); } for (int row = bottom; row > top; row --) { res.push_back(matrix[row][left]); } } left ++, right --, top ++, bottom --; }
return res; } };
class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { if (matrix.size() == 0 || matrix[0].size() == 0) return vector<int>();
int rows = matrix.size(), cols = matrix[0].size(); int total = rows * cols; vector<int> res(total); vector<vector<bool>> visited(rows, vector<bool>(cols)); int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 }; int r = 0, c = 0, d = 1; for (int i = 0; i < total; i ++) { res[i] = matrix[r][c]; visited[r][c] = true; int a = r + dx[d], b = c + dy[d]; if (a < 0 || a >= rows || b < 0 || b >= cols || visited[a][b]) { d = (d + 1) % 4; a = r + dx[d], b = c + dy[d]; } r = a, c = b; }
return res; } };
|