-
Notifications
You must be signed in to change notification settings - Fork 344
New issue
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
螺旋矩阵 II-59 #113
Labels
Comments
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let top = 0, bottom =n-1
let left = 0, right = n-1
let res = []
for(let i=0;i<n;i++) res[i] = []
let cur = 1, total = n*n
while(cur<=total){
for(let i=left;i<=right;i++) res[top][i] = cur++ // 从左到右
top++
for(let i=top;i<=bottom;i++) res[i][right] = cur++ // 从上到下
right--
for(let i=right;i>=left;i--) res[bottom][i] = cur++ // 从右到左
bottom--
for(let i=bottom;i>=top;i--) res[i][left] = cur++ // 从下到上
left++
}
return res
}; |
let generateMatrix = function(n) {
let num = 1;
let matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
let left = 0,right = n-1,bottom = n-1,top =0;
while(num <= n*n){
//填充上行从左到右
for(let i = left;i<=right;i++){
matrix[top][i] = num;
num ++;
}
top++;
//填充右列从上到下
for(let i = top;i<=bottom;i++){
matrix[i][right] = num;
num++;
}
right--;
//填充下行从右到左
for(let i = right;i>=left;i--){
matrix[bottom][i] = num;
num ++;
}
bottom--;
//填充左列从下到上
for(let i = bottom;i>=top;i--){
matrix[i][left] = num;
num++;
}
left++;
}
return matrix
}; |
function fn2(n: number) {
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0))
const total = n * n
let i = 0, j = 0, count = 2
matrix[0][0] = 1
while(count <= total) {
while(j < n - 1 && matrix[i][j + 1] === 0) matrix[i][++j] = count ++
while(i < n - 1 && matrix[i + 1][j] === 0) matrix[++i][j] = count ++
while(j > 0 && matrix[i][j - 1] === 0) matrix[i][--j] = count ++
while(i > 0 && matrix[i - 1][j] === 0) matrix[--i][j] = count ++
}
return matrix
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这题基本上就是和 螺旋矩阵-54 反过来了,54 题是把值按顺序输出出来,这题是按顺序重建二维数组,稍作改动即可完成。
The text was updated successfully, but these errors were encountered: