Created
February 6, 2022 08:21
-
-
Save SLIB53/486bf9cbd6d6ad450a29bca67dfb4f1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} matrix | |
* @return {number[][]} Indexes as an array of (row, col) tuples. | |
*/ | |
const spiralOrder = (matrix) => { | |
let indexes = []; | |
const width = matrix[0].length; | |
const height = matrix.length; | |
for (let ring = 0; ; ring++) { | |
const wEnd = width - 1 - ring; | |
const hEnd = height - 1 - ring; | |
if (ring > wEnd || ring > hEnd) break; | |
// Top | |
for (let i = ring; i <= wEnd; i++) indexes.push([ring, i]); | |
// Right | |
for (let i = ring + 1; i <= hEnd; i++) indexes.push([i, wEnd]); | |
// Bottom | |
if (hEnd != ring) | |
for (let i = wEnd - 1; i >= ring; i--) indexes.push([hEnd, i]); | |
// Left | |
if (ring != wEnd) | |
for (let i = hEnd - 1; i > ring; i--) indexes.push([i, ring]); | |
} | |
return indexes; | |
}; | |
/** | |
* @param {number[]} matrix | |
* @param {number} k | |
*/ | |
const spiralRotate = (matrix, k) => { | |
const so = spiralOrder(matrix); | |
let counter = 0; | |
for (let i = 0; i < so.length && counter < so.length; i++) { | |
let temp = matrix[so[i][0]][so[i][1]]; | |
for (let j = i; ; ) { | |
const offset = (j + k) % so.length; | |
const tempCandidate = matrix[so[offset][0]][so[offset][1]]; | |
matrix[so[offset][0]][so[offset][1]] = temp; | |
temp = tempCandidate; | |
counter++; | |
j = offset; | |
if (j == i) break; | |
} | |
} | |
}; | |
// Main | |
let matrix = [ | |
[1, 2, 3], | |
[8, 9, 4], | |
[7, 6, 5], | |
]; | |
spiralRotate(matrix, 1); | |
// matrix: | |
// [ | |
// [9, 1, 2], | |
// [7, 8, 3], | |
// [6, 5, 4], | |
// ]; | |
console.log(JSON.stringify(matrix)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment