養(yǎng)老網(wǎng)站建設方案上海企業(yè)seo
螺旋矩陣
題目
給你一個正整數(shù) n
,生成一個包含 1
到 n2
所有元素,且元素按順時針順序螺旋排列的 n x n
正方形矩陣 matrix
。
示例 1:
輸入:n = 3
輸出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
輸入:n = 1
輸出:[[1]]
按層模擬解題思路
這段代碼是一個生成螺旋矩陣的算法。它使用一個二維數(shù)組matrix來表示n行n列的矩陣,通過循環(huán)來逐步填充矩陣中的元素。
- 首先,定義四個變量left、right、top和bottom,分別表示當前螺旋矩陣的左邊界、右邊界、上邊界和下邊界。另外,還有一個變量num用于記錄當前要填充的數(shù)字。
- 然后,通過一個while循環(huán)來依次填充矩陣中的元素。循環(huán)條件是num小于等于n*n,也就是還沒有填充完所有的元素。
- 在循環(huán)中:
- 首先從左到右填充上邊界,即從left到right-1,將數(shù)字num依次賦值給matrix[top][i],同時num遞增。將top遞增,表示上邊界向下移動一行。
- 然后從上到下填充右邊界,即從top到bottom-1,將數(shù)字num依次賦值給matrix[i][right],同時num遞增。將right遞減,表示右邊界向左移動一列。
- 然后從右到左填充下邊界,即從right到left+1,將數(shù)字num依次賦值給matrix[bottom][i],同時num遞增。將bottom遞減,表示下邊界向上移動一行。
- 最后從下到上填充左邊界,即從bottom到top+1,將數(shù)字num依次賦值給matrix[i][left],同時num遞增。將left遞增,表示左邊界向右移動一列。循環(huán)回到開始,直到所有的元素都被填充完。
- 最后,返回生成的螺旋矩陣matrix。
代碼
/*** @param {number} n* @return {number[][]}*/
var generateMatrix = function(n) {let matrix = [];for (let i = 0; i < n; i++) {matrix.push([]);}let left = 0, right = n - 1, top = 0, bottom = n - 1;let num = 1;while (num <= n*n) {for (let i = left; i <= right; i++) matrix[top][i] = num++;top++;for (let i = top; i <= bottom; i++) matrix[i][right] = num++;right--;for (let i = right; i >= left; i--) matrix[bottom][i] = num++;bottom--;for (let i = bottom; i >= top; i--) matrix[i][left] = num++;left++;}console.log(matrix);return matrix;
};
模擬法解題思路
這段代碼是用JavaScript編寫的生成螺旋矩陣的函數(shù)。它使用一個二維數(shù)組matrix
來表示n行n列的矩陣,通過循環(huán)逐步填充矩陣中的元素。
- 首先,定義了一些變量。
maxNum
表示最大的數(shù)字,也就是矩陣中元素的個數(shù);curNum
表示當前要填充的數(shù)字;matrix
是一個大小為n x n的二維數(shù)組,初始值都為0;row
和column
表示當前要填充的位置;directions
是一個數(shù)組,表示四個方向的偏移量,分別是右、下、左、上;directionIndex
表示當前的方向。 - 然后,通過一個while循環(huán)來依次填充矩陣中的元素。循環(huán)條件是
curNum
小于等于maxNum
,也就是還沒有填充完所有的元素。 - 在循環(huán)中:
- 首先將當前位置的值設置為
curNum
,然后curNum
遞增。 - 接著,計算下一個位置的行號和列號,即
nextRow = row + directions[directionIndex][0]
和nextColumn = column + directions[directionIndex][1]
。 - 如果下一個位置超出了矩陣的邊界或者已經(jīng)有值了(即不為0),則說明需要改變方向。這里通過
directionIndex = (directionIndex + 1) % 4
來順時針旋轉到下一個方向。 - 最后,更新
row
和column
的值為下一個位置的行號和列號,進入下一次循環(huán)。
- 首先將當前位置的值設置為
- 最終,返回生成的螺旋矩陣
matrix
。
代碼
var generateMatrix = function(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;
};