We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
出处:LeetCode 算法第59题 给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 示例: 输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
出处:LeetCode 算法第59题
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
同螺旋矩阵
/** * @param {number} n * @return {number[][]} */ var generateMatrix = function (n) { var result = []; for (var i = 0; i < n; i++) { result[i] = []; } var row = n - 1; var col = n - 1; var r = 0; var c = 0; var current = 1; while (r <= row && c <= col) { for (var i = r; i <= col; i++) { result[r][i] = current++; } r++; for (var i = r; i <= row; i++) { result[i][col] = current++; } col--; if (r <= row) { for (var i = col; i >= c; i--) { result[row][i] = current++; } row--; } if (c <= col) { for (var i = row; i >= r; i--) { result[i][c] = current++; } c++; } } return result; }; console.log(generateMatrix(3));
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
同螺旋矩阵
解答
The text was updated successfully, but these errors were encountered: