题解 | #牛牛的顺时针遍历#
牛牛的顺时针遍历
https://www.nowcoder.com/practice/4c6722d907b147c7b73b51bdac768374
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix int整型vector<vector<>>
* @return int整型vector
*/
vector<int> spiralOrder(vector<vector<int> >& matrix) {
// write code here
vector<int> res;
int x = 0, y = 0;
int L = matrix.size(), W = matrix[0].size();
while (true) {
res.push_back(matrix[x][y]);
int step = W - 1;
if(step == 0) break;
// right
while(step!=0){
y++;
step--;
res.push_back(matrix[x][y]);
}
// down
step = L-1;
if(step == 0) break;
while(step!=0){
x++;
step--;
res.push_back(matrix[x][y]);
}
// left
step = W - 1;
while(step!=0){
y--;
step--;
res.push_back(matrix[x][y]);
}
// up
step = L - 2;
if(step == 0) break;
while(step!=0){
x--;
step--;
res.push_back(matrix[x][y]);
}
y++;
W-=2;
L-=2;
if(W==0 || L==0) break;
}
return res;
}
};
查看11道真题和解析
