zoukankan      html  css  js  c++  java
  • 59. 螺旋矩阵 II

    题目:给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 

    示例 1:

    输入:n = 3
    输出:[[1,2,3],[8,9,4],[7,6,5]]

    题解:

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            int maxNum = n * n;
            int curNum = 1;
            vector<vector<int>> matrix(n, vector<int>(n));
            int row = 0, column = 0;
            vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};  // 右下左上
            int directionIndex = 0;
            while (curNum <= maxNum) {
                matrix[row][column] = curNum;
                curNum++;
                int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
                if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || matrix[nextRow][nextColumn] != 0) {
                    directionIndex = (directionIndex + 1) % 4;  // 顺时针旋转至下一个方向
                }
                row = row + directions[directionIndex][0];
                column = column + directions[directionIndex][1];
            }
            return matrix;
        }
    };
  • 相关阅读:
    mysql的复制
    web页面请求历程
    django工作原理简介
    http协议
    路由器和交换机的区别
    OSI七层模型
    TCP/IP协议总结
    IO复用
    僵尸进程和孤儿进程
    java源代码如何打成jar包
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/14541830.html
Copyright © 2011-2022 走看看