顺时针打印矩阵
顺时针打印矩阵
http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a
顺时针打印矩阵,思路是首先用左上角和右下角的坐标作为边界限制,第一次从左到右打印;第二次从上到下打印;第三次从右到左打印;第四次从下到上打印;需要注意每次循环打印的边界值控制,尤其是第三次和第四次要判断是否溢出。
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> result;
int rows = matrix.size();
int cols = matrix[0].size();
if(rows == 0 && cols == 0){
return result;
}
int left = 0;
int top = 0;
int right = cols - 1;
int buttom = rows - 1;
while(left <= right && top <= buttom){
//从左到右
for(int i = left; i <= right; i++){
result.push_back(matrix[top][i]);
}
//从上到下
for(int i = top + 1; i <= buttom; i++){
result.push_back(matrix[i][right]);
}
//从右到左
if(top != buttom){
for(int i = right - 1; i >= left; i--){
result.push_back(matrix[buttom][i]);
}
}
//从下到上
if(right != left){
for(int i = buttom - 1; i > top; i--){
result.push_back(matrix[i][left]);
}
}
left++;
top++;
right--;
buttom--;
}
return result;
}
}; 

