classSolution { public: vector<int> printMatrix(vector<vector<int>> matrix) { int row = matrix.size(); int col = matrix[0].size(); vector<int> result; // 用于存放输出的结果 if (row == 0 && col == 0) // 判断矩阵是否为空 return result; int left = 0, right = col -1, top = 0, bottom = row - 1; while (left <= right && top <= bottom) // 判断矩阵是否遍历完 { for (int i = left; i <= right; i++) //从左向右,注意i 的范围 result.push_back(matrix[top][i]); for (int i = top + 1; i <= bottom; i++) // 从上到下,注意i的范围 result.push_back(matrix[i][right]); if (top != bottom) //若top == bottom 则没有必要再从右向左遍历,因为已经遍历过了 { for (int i = right - 1; i >= left; i--) // 从右向左,注意i的范围。 result.push_back(matrix[bottom][i]); } if (left != right) // 若left==right则没必要从下到上遍历,因为已经遍历过了 { for (int i = bottom - 1; i > top; i--)// 从下向上,注意i的范围 result.push_back(matrix[i][left]); } left++,right--,top++,bottom--; } return result; } };