You are viewing a single comment's thread. Return to all comments →
A concise version, with no duplicate rotation. implemantation in JS/TS.
function matrixRotation(matrix: number[][], R: number): void { const rows = matrix.length const cols = matrix[0].length let top= 0, left =0, right = cols -1, bottom = rows-1 while(top < bottom && left<right) { const p = 2 * (right - left + bottom - top); const rotations = R % p; for(let r=0; r<rotations;r++) { const first_value = matrix[top][left]; // rotate top for(let i = left; i< right; i++) { matrix[top][i] = matrix[top][i+1] } // rotate right for(let i = top; i< bottom; i++ ) { matrix[i][right] = matrix[i+1][right] } // rotate bottom for(let i = right; i >left ;i-- ) { matrix[bottom][i] = matrix[bottom][i-1] } // rotate left for(let i = bottom; i>top; i--) { matrix[i][left] = matrix[i-1][left] } matrix[top+1][left] = first_value } ++top; ++left; --bottom; --right; } matrix.forEach(v=> { console.log(...v) }) }
Seems like cookies are disabled on this browser, please enable them to open this website
Matrix Layer Rotation
You are viewing a single comment's thread. Return to all comments →
A concise version, with no duplicate rotation. implemantation in JS/TS.