每日一题,防止痴呆 = =
一、题目大意
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
二、题目思路以及AC代码
思路:模拟
这题还挺有意思的,就是模拟就可以了,和最简单的机器人一样,设定一个方向,一开始一直朝着那个方向走,当超出边界或者遇到已经访问过的元素的时候,就向右拐,直到最后我们如果拐了四个方向还是没法向下走,那么就说明所有的元素已经都遍历完了。思路就挺简单的。
当然,还有一个思路就是按照层遍历,最外面的元素都是第一层,次外层是第二层,我们只需要按照顺时针的顺序遍历每层的元素,最终得到的就是和上述一样的效果,可以看一下遍历的图。
AC代码
这里我只实现了第一种的思路,因为看起来比较有意思 = =,我这里直接用了一个类封装,这样看起来是不是更像一个小机器人了 ^_^
#define FLAG -2147483648
class Matrix {
private:
vector<vector<int>> matrix;
int direction[2]; // 上,下,左,右
int x, y; // 当前位置
int rows, cols;
public:
Matrix(vector<vector<int>>& matrix) {
this->matrix = matrix;
rows = matrix.size();
cols = matrix[0].size();
direction[0] = 0; // 右
direction[1] = 1;
x = 0;
y = 0;
}
void next_direction() {
if (direction[0] == 0 && direction[1] == 1) {
direction[0] = 1; direction[1] = 0;
}
else if (direction[0] == 1 && direction[1] == 0) {
direction[0] = 0; direction[1] = -1;
}
else if (direction[0] == 0 && direction[1] == -1) {
direction[0] = -1; direction[1] = 0;
}
else if (direction[0] == -1 && direction[1] == 0) {
direction[0] = 0; direction[1] = 1;
}
}
int next() {
int xx = x + direction[0];
int yy = y + direction[1];
int idx = 0;
while (xx < 0 || xx >= rows || yy < 0 || yy >= cols || matrix[xx][yy] == FLAG) {
next_direction();
xx = x + direction[0];
yy = y + direction[1];
if (idx >= 3) return FLAG;
idx++;
}
int temp = matrix[xx][yy];
matrix[xx][yy] = FLAG;
x = xx;
y = yy;
return temp;
}
};
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (!matrix.size()) return vector<int>();
vector<int> res;
res.push_back(matrix[0][0]);
matrix[0][0] = FLAG;
Matrix m(matrix);
int nextone = 0;
while ((nextone = m.next()) != FLAG) {
res.push_back(nextone);
}
return res;
}
};
如果有问题,欢迎大家指正!!!