m0_61574664 2022-02-07 14:36 采纳率: 87.1%
浏览 77
已结题

螺旋矩阵,简单题,有几个问题

class Solution {
private:
static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
vector spiralOrder(vector<vector>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}

    int rows = matrix.size(), columns = matrix[0].size();
    vector<vector<bool>> visited(rows, vector<bool>(columns));
    int total = rows * columns;
    vector<int> order(total);

    int row = 0, column = 0;
    int directionIndex = 0;
    for (int i = 0; i < total; i++) {
        order[i] = matrix[row][column];
        visited[row][column] = true;
        int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
        if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
            directionIndex = (directionIndex + 1) % 4;
        }
        row += directions[directionIndex][0];
        column += directions[directionIndex][1];
    }
    return order;
}

};
这是力扣第54道原题,螺旋矩阵的官方答案的方法一模拟法,我有几个问题,来个认真负责的大佬
1.directionIndex = (directionIndex + 1) % 4;这个是什么意思,有什么作用,%4我很困惑,希望讲的详细一点
2.static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};为什么要用静态static constexpr int呢,我设置一个vector<vector<>>不好吗
3.row += directions[directionIndex][0];column += directions[directionIndex][1];我看这个我蒙了,我知道这是代表位移,但是他是怎么判断出你应该往左还是往右的往上还是往下的,我知道前面有个if,但是nextrow在if之前啊,希望讲的详细一点

  • 写回答

3条回答 默认 最新

  • 爱晚乏客游 2022-02-07 15:00
    关注

    1.
    先看int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
    这句话你应该知道吧,也就是下一个点该是什么,directionIndex=0的时候这句话就是就是x方向+1,y方向不动,directionIndex=1的时候这句话就是y+1,x不动,directionIndex等于2和3同理,所以directions就是方向,该向哪个方向移动,由directionIndex的值来控制。所以directionIndex的值是不能超过3,%4就是保证他的取值为0,1,2,3.
    directionIndex = (directionIndex + 1) % 4;这个是用来判断螺旋矩阵前景方向的,当前方向上,下一个位置是出边界了还是已经遍历完毕了,如果遍历或者越界,则需要拐弯,而从题意和directions设计来看,旋转方向是右-》下-》左-》上-》右这种顺序执行的,所以+1代表下一个方向是哪个方向,%4求余是为了保证directionIndex取值不超过3.举例来说就是假设当前方向是向上,directionIndex=3,走到底之后下一个方向是向右,(directionIndex + 1) % 4=0,directionIndex =0的时候directions[0]=[0,1],代入最上面的那行代码中你就会发现y值不变,x值加1,那么他的方向就是向右移动。

    2.
    constexpr关键字的作用和const的区别,你用vector当然可以啊,但是vector可能会被修改的,不修改就一点问题都没有
    https://www.zhihu.com/question/35614219/answer/798370856
    3.
    至于第三点,你看懂了我上面说的directionIndex 和directions的作用你就知道了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 2月15日
  • 已采纳回答 2月7日
  • 创建了问题 2月7日

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装
  • ¥40 复杂的限制性的商函数处理