-
-
Notifications
You must be signed in to change notification settings - Fork 235
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
打印一个螺旋式矩阵 #217
Comments
去提pr呀,写到issue里面发现不了 |
|
var spiralOrder = function(matrix) {
let n = matrix.length,m = matrix[0].length;
let res = [];
let left = 0, top = 0 , right = m - 1, bottom = n - 1;
while(left < right && top < bottom) {
for(let i = left ; i < right ; i ++) res.push(matrix[top][i])
for(let i = top ; i < bottom ; i ++) res.push(matrix[i][right])
for(let i = right ; i > left ; i --) res.push(matrix[bottom][i])
for(let i = bottom ; i > top ; i --) res.push(matrix[i][left])
left ++
top ++
right --
bottom --
}
if(top === bottom) {
for(let i = left ; i <= right ; i ++) res.push(matrix[top][i])
} else if(left === right){
for(let i = top ; i <= bottom ; i ++) res.push(matrix[i][left])
}
return res
}; |
function generateMatrix(n) {
const arr = new Array(n).fill(0).map(() => new Array(n).fill(0));
// 奇数单独设置中间元素
if (n % 2) {
const mid = Math.floor(n / 2);
arr[mid][mid] = n * n;
}
// 循环圈数
let loop = Math.floor(n / 2);
// 用于控制每次循环遍历边的长度
let offset = 1;
let num = 1;
let startX = 0;
let startY = 0;
while (loop--) {
for (let k = startY; k < n - offset; k++) {
arr[startX][k] = num++;
}
for (let k = startX; k < n - offset; k++) {
arr[k][n - offset] = num++;
}
for (let k = n - offset; k > startX; k--) {
arr[n - offset][k] = num++;
}
for (let k = n - offset; k > startY; k--) {
arr[k][startY] = num++;
}
startX++;
startY++;
offset++;
}
return arr;
}
generateMatrix(7); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
--- examples
这就是返回的顺时针的螺旋式矩阵啦~~
以下是代码部分:
The text was updated successfully, but these errors were encountered: