AcWing 40. 顺时针打印矩阵
原题链接
中等
作者:
葱花鸡蛋
,
2020-04-02 15:47:36
,
所有人可见
,
阅读 482
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int>ans; ans.clear();
int c, r = matrix.size();
if (r != 0) c = matrix[0].size();
else return ans;
vector<vector<bool> >bord(r, vector<bool>(c, false));
if (r * c == 0) return ans;
int count = 1;
int flag = 0;
int xpos = 0, ypos = 0;
ans.push_back(matrix[0][0]); bord[0][0] = true;
while (count != r * c) {
switch (flag) {
case 0:while(ypos + 1 < c && !bord[xpos][ypos + 1]){count++;ans.push_back(matrix[xpos][++ ypos]);bord[xpos][ypos] = true;}break;
case 1:while(xpos + 1 < r && !bord[xpos + 1][ypos]){count++;ans.push_back(matrix[++ xpos][ypos]);bord[xpos][ypos] = true;}break;
case 2:while(ypos - 1 >= 0 && !bord[xpos][ypos - 1]){count++;ans.push_back(matrix[xpos][ --ypos]);bord[xpos][ypos] = true;}break;
case 3:while(xpos - 1 >= 0 && !bord[xpos - 1][ypos]){count++;ans.push_back(matrix[-- xpos][ypos]);bord[xpos][ypos] = true;}break;
}
flag ++; flag %= 4;
}
return ans;
}
};