漩涡型二维数组
作者:xie392地址:https://v.douyin.com/ieaCawgS/更新时间:2024-12-21
案例代码
1/**2* 漩涡型二维数组3* @param {number} col 列4* @param {number} row 行5* @returns {Array} 二维数组6* @example7* 1 2 3 48* 10 11 12 59* 9 8 7 610*/11function vortexMatrix(col, row) {12// 创建二维数组 初始值为013const matrix = Array.from({ length: row }, () => Array.from({ length: col }, () => 0))1415// 定义上下左右边界16let top = 017let bottom = row - 118let left = 019let right = col - 12021// 定义当前位置22let current = 12324// 循环填充25while (current <= col * row) {26// 从左到右27for (let i = left; i <= right; i++) {28matrix[top][i] = current++29}30top++3132// 从上到下33for (let i = top; i <= bottom; i++) {34matrix[i][right] = current++35}36right--3738// 从右到左39for (let i = right; i >= left; i--) {40matrix[bottom][i] = current++41}42bottom--4344// 从下到上45for (let i = bottom; i >= top; i--) {46matrix[i][left] = current++47}48left++49}5051// 打印52matrix.forEach(row => {53console.log(row.join(' '))54})5556return matrix57}5859vortexMatrix(4, 3)
输出结果:
11 2 3 4210 13 12 539 8 7 6
目录