以下代码为javascript中二维数组旋转变换的各种实现:
主对角线翻转(左上至右下)
const diagonal = (matrix) => {
const len = matrix.length;
for (let i = 0; i < len; ++i) {
for (let j = 0; j < i; ++j) {
const temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
};
次对角线(右上至左下)
1 2 3
4 5 6
7 8 9
[0,0] => [2,2]
[0,1] => [1,2]
[1,0] => [2,1]
// [i, j] => [len - 1 - j, len - 1 - i]
const counterDiagonal = (matrix) => {
const len = matrix.length;
for (let i = 0; i < len; ++i) {
for (let j = 0; j < len - i - 1; ++j) {
const temp = matrix[i][j];
matrix[i][j] = matrix[len - 1 - j][len - 1 - i];
matrix[len - 1 - j][len - 1 - i] = temp;
}
}
};
水平翻转(上到下)
const horizontal = (matrix) => {
const len = matrix.length;
for (let i = 0; i < len / 2; ++i) {
for (let j = 0; j < len; ++j) {
const temp = matrix[i][j];
matrix[i][j] = matrix[len - 1 - i][j];
matrix[len - 1 - i][j] = temp;
}
}
};
垂直翻转(左到右)
const vertical = (matrix) => {
const len = matrix.length;
for (let i = 0; i < len; ++i) {
for (let j = 0; j < len / 2; ++j) {
const temp = matrix[i][j];
matrix[i][j] = matrix[i][len - 1 - j];
matrix[i][len - 1 - j] = temp;
}
}
};
网友评论