leetcode 59题 螺旋矩阵 II
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例1
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例2
输入:n = 1
输出:[[1]]
思路
顺时针打印,控制上下左右的边界
代码
/**
* @param {number} n
* @return {number[][]}
*/
function generateMatrix(n) {
const maxNum = n * n;
let curNum = 1;
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
let row = 0, column = 0;
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
let directionIndex = 0;
while (curNum <= maxNum) {
matrix[row][column] = curNum;
curNum++;
const 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;
}
复杂度分析:
- 时间复杂度: O(N)
- 空间复杂度:O(N^2)
FEATURED TAGS
前端开发
H5
JavaScript
设计模式
browser
jQuery
源码分析
生活
leetcode
Array
Stack
Queue
Linked List
剑指offer
Binary Search Tree
Binary Tree
Breadth-First Search
Depth-First Search
String
Set
Binary Search
Sliding Window
Backtracking
Dynamic Programming
Two Pointers
Union Find
Sort
Bit Operation
Recursion
Map
Graph
Search
Hash
LinkedList
复盘
QuickSort
Trie
Design
MinHeap
Traverse
Min Heap
Node.js
BackEnd
SQL
MySQL
Design Patterns
Network
计算机网络
Python
SVG