每日算法:螺旋矩陣
作者:sisterAn
給定一個(gè)正整數(shù) n,生成一個(gè)包含 1 到 n2 所有元素,且元素按順時(shí)針順序螺旋排列的正方形矩陣。
本文轉(zhuǎn)載自微信公眾號(hào)「三分鐘學(xué)前端」,作者sisterAn 。轉(zhuǎn)載本文請(qǐng)聯(lián)系三分鐘學(xué)前端公眾號(hào)。
給定一個(gè)正整數(shù) n,生成一個(gè)包含 1 到 n2 所有元素,且元素按順時(shí)針順序螺旋排列的正方形矩陣。
示例:
- 輸入: 3
- 輸出:
- [
- [ 1, 2, 3 ],
- [ 8, 9, 4 ],
- [ 7, 6, 5 ]
- ]
解答
- const generateMatrix = (n) => {
- // 定義一個(gè)二維數(shù)組進(jìn)行數(shù)據(jù)保存
- const result = []
- for (let i = 0; i < n; i++) {
- result.push(new Array(n))
- }
- let left = 0
- let right = n - 1
- let top = 0
- let bottom = n - 1
- let current = 1, max = n * n
- while(current <= max) {
- // 上面從左到右
- for (let i = left; i <= right; i++) {
- result[top][i] = current++
- }
- top ++
- // 右邊從上到下
- for (let i = top; i <= bottom; i++) {
- result[i][right] = current++
- }
- right --
- // 下邊從右到左
- for (let i = right; i >= left; i--) {
- result[bottom][i] = current++
- }
- bottom --
- // 左邊從下到上
- for (let i = bottom; i >= top; i--) {
- result[i][left] = current++
- }
- left ++
- }
- return result
- }
leetcode:https://leetcode-cn.com/problems/spiral-matrix-ii
責(zé)任編輯:武曉燕
來源:
三分鐘學(xué)前端