Created
June 19, 2024 14:37
-
-
Save theArina/c00d5a241c12ee9c1ab36f5c01125d20 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
function spiralMatrixTraverse(matrix) { | |
if (matrix.length === 0) { | |
return []; | |
} | |
const result = []; | |
let top = 0; | |
let bottom = matrix.length - 1; | |
let left = 0; | |
let right = matrix[0].length - 1; | |
while (top <= bottom && left <= right) { | |
for (let i = left; i <= right; i++) { | |
result.push(matrix[top][i]); | |
} | |
top++; | |
for (let i = top; i <= bottom; i++) { | |
result.push(matrix[i][right]); | |
} | |
right--; | |
if (top <= bottom) { | |
for (let i = right; i >= left; i--) { | |
result.push(matrix[bottom][i]); | |
} | |
bottom--; | |
} | |
if (left <= right) { | |
for (let i = bottom; i >= top; i--) { | |
result.push(matrix[i][left]); | |
} | |
left++; | |
} | |
} | |
return result; | |
} | |
const tests = [ | |
{ | |
name: '3x3', | |
matrix: [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
], | |
expectedResult: [1, 2, 3, 6, 9, 8, 7, 4, 5], | |
}, | |
{ | |
name: '4x3', | |
matrix: [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
[10, 11, 12], | |
], | |
expectedResult: [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8], | |
}, | |
{ | |
name: '2x4', | |
matrix: [ | |
[1, 2, 3, 4], | |
[5, 6, 7, 8], | |
], | |
expectedResult: [1, 2, 3, 4, 8, 7, 6, 5], | |
}, | |
{ | |
name: '1x5', | |
matrix: [ | |
[1, 2, 3, 4, 5], | |
], | |
expectedResult: [1, 2, 3, 4, 5], | |
}, | |
{ | |
name: '5x1', | |
matrix: [ | |
[1], | |
[2], | |
[3], | |
[4], | |
[5] | |
], | |
expectedResult: [1, 2, 3, 4, 5], | |
}, | |
]; | |
tests.forEach(({name, matrix, expectedResult}) => { | |
const myResult = spiralMatrixTraverse(matrix); | |
console.log(`----- Test ${name} -----`); | |
console.log('Expected result:', expectedResult); | |
console.log(' Actual result:', myResult); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment