/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
// 获取行列长度
const m = matrix.length;
const n = matrix[0].length;
// 提前储存首行首列中是否有0的信息
const firstRowHasZero = matrix[0].includes(0); // 首行直接使用include进行判断
const firstColHasZero = matrix.some(row => row[0] === 0); // 首列无法使用include,使用some进行遍历判断
// 跳过首行首列进行遍历:如果该位置为0就将该位置的对应首行和首列的位置置0
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
if (matrix[i][j] === 0) matrix[i][0] = matrix[0][j] = 0;
}
}
// 跳过首行首列进行置0:如果该位置对应首行或首列的位置为0就将该位置置0
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
if (matrix[i][0] === 0 || matrix[0][j] === 0) matrix[i][j] = 0;
}
}
// 首列判断置0:遍历每行首位置0
if (firstColHasZero) {
for (const row of matrix) {
row[0] = 0;
}
}
// 首行判断置0:直接使用fill填充
if (firstRowHasZero) matrix[0].fill(0);
};
js复制代码
var setZeroes = function(matrix) {
const m = matrix.length, n = matrix[0].length, row1 = matrix[0].includes(0), col1 = matrix.some(col => col[0] === 0);
for (let i = 1; i < m; i++) for (let j = 1; j < n; j++) if (matrix[i][j] === 0) matrix[i][0] = matrix[0][j] = 0;
for (let i = 1; i < m; i++) for (let j = 1; j < n; j++) if (matrix[i][0] === 0 || matrix[0][j] === 0) matrix[i][j] = 0;
if (row1) matrix[0].fill(0);
if (col1) for (let row of matrix) row[0] = 0;
};
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
const m = matrix.length, n = matrix[0].length;
let top = 0;
let bottom = m - 1;
let left = 0;
let right = n - 1;
let ans = [];
while (top <= bottom && left <= right) {
for (let j = left; j <= right; j++) {
ans.push(matrix[top][j]);
}
top++;
for (let i = top; i <= bottom; i++) {
ans.push(matrix[i][right]);
}
right--;
if (top <= bottom) {
for (let j = right; j >= left; j--) {
ans.push(matrix[bottom][j])
}
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) {
ans.push(matrix[i][left]);
}
left++;
}
}
return ans;
};