Skip to content

Commit 6380a7a

Browse files
authored
Update 1914-cyclically-rotating-a-gridsubmissions.js
1 parent 38124f4 commit 6380a7a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

1914-cyclically-rotating-a-gridsubmissions.js

+42
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,45 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @param {number} k
4+
* @return {number[][]}
5+
*/
6+
const rotateGrid = function(grid, k) {
7+
const m = grid.length, n = grid[0].length
8+
let top = 0, left = 0, right = n - 1, bottom = m - 1
9+
while(top < bottom && left < right) {
10+
const num = (right - left + 1) * 2 + (bottom - top + 1) * 2 - 4
11+
let rem = k % num
12+
while(rem) {
13+
const tmp = grid[top][left]
14+
// top
15+
for(let i = left; i < right; i++) {
16+
grid[top][i] = grid[top][i + 1]
17+
}
18+
// right
19+
for(let i = top; i < bottom; i++) {
20+
grid[i][right] = grid[i + 1][right]
21+
}
22+
// bottom
23+
for(let i = right; i > left; i--) {
24+
grid[bottom][i] = grid[bottom][i - 1]
25+
}
26+
// left
27+
for(let i = bottom; i > top; i--) {
28+
grid[i][left] = grid[i - 1][left]
29+
}
30+
grid[top + 1][left] = tmp
31+
rem--
32+
}
33+
left++
34+
top++
35+
right--
36+
bottom--
37+
}
38+
return grid
39+
};
40+
41+
// another
42+
143
/**
244
* @param {number[][]} grid
345
* @param {number} k

0 commit comments

Comments
 (0)