54,螺旋矩阵
题目描述
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
题解
思路:
主要的思路:
一圈一圈的去遍历
设置四个变量,分别是上下左右的大小
代码:
var spiralOrder = function (matrix) {
let m = matrix.length, n = matrix[0].length, res = []
let top = 0, bottom = m - 1, right = n - 1, left = 0
// 每一圈遍历的条件
while (top <= bottom && left <= right) {
// 上面一层,从左往右
for (let j = left; j <= right; j++) {
res.push(matrix[top][j])
}
// 右边一列,从上到下
for (let i = top + 1; i <= bottom; i++) {
res.push(matrix[i][right])
}
// 判断是否是一层或者是一列的情况,如果是一层或者是一列,那就不再执行下面的, 避免重复遍历
if (left < right && top < bottom) {
// 下面一层,从右往左
for (let j = right - 1; j >= left; j--) {
res.push(matrix[bottom][j])
}
// 左边一列从下往上
for(let i = bottom - 1;i > top;i--){
res.push(matrix[i][left])
}
}
[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1]
}
return res
}
原题链接
59, 螺旋矩阵II
题目描述
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
代码
思路和第一道题都是一样的,需要单独去维护一个k,去计数。
var generateMatrix = function(n) {
let res = new Array(n).fill(0).map(v => new Array(n).fill(0))
let k = 1,left = 0,right = n - 1, top = 0,bottom = n - 1
while(left <= right && top <= bottom){
for(let i = left; i <= right;i++){
res[top][i] = k
k++
}
for(let j = top + 1;j <= bottom;j++){
res[j][right] = k
k++
}
if(top < bottom && left < right){
for(let i = right - 1;i >= left;i--){
res[bottom][i] = k
k++
}
for(let j = bottom - 1; j > left;j--){
res[j][left] = k
k++
}
}
[left, right, top, bottom] = [left + 1, right - 1,top + 1,bottom - 1]
}
return res
};