模拟顺时针画矩阵的过程:
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
由外向内一圈一圈这么画下去
/** * 生成一个包含从1到n*n的数字的矩阵 * @param {number} n - 矩阵的大小,为正整数 * @return {number[][]} - 返回一个n x n的二维数组,数组中的每个元素为从1到n*n的递增数字 */ var generateMatrix = function (n) { let matrix = new Array(n); for (let i = 0; i < n; i++) { matrix[i] = new Array(n).fill(0); } let top = 0, bottom = n - 1, left = 0, right = n - 1; let direction = [[-1, 0], [0, 1], [1, 0], [0, -1]]; // 上、右、下、左四个方向 let index = 0; while (top <= bottom && left <= right) { // 沿着当前方向遍历边界 for (let i = left; i <= right; i++) { matrix[top][i] = ++index; } top++; for (let i = top; i <= bottom; i++) { matrix[i][right] = ++index; } right--; if (top <= bottom) { for (let i = right; i >= left; i--) { matrix[bottom][i] = ++index; } bottom--; } if (left <= right) { for (let i = bottom; i >= top; i--) { matrix[i][left] = ++index; } left++; } } return matrix; };
标签:59,matrix,--,矩阵,II,++,let,left From: https://www.cnblogs.com/zx618/p/18339449