-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathCyclically Rotating a Grid.js
99 lines (77 loc) · 2.4 KB
/
Cyclically Rotating a Grid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var rotateGrid = function(grid, k) {
const m = grid.length;
const n = grid[0].length;
let startRow = 0;
let endRow = m - 1;
let startCol = 0;
let endCol = n - 1;
while (startRow <= endRow && startCol <= endCol) {
let currRowStart = startRow;
let currRowEnd = endRow;
let currColStart = startCol;
let currColEnd = endCol;
const vals = [];
// Top
for (let col = currColStart; col <= currColEnd; ++col) {
const val = grid[currRowStart][col];
vals.push(val);
}
++currRowStart;
// Right
for (let row = currRowStart; row <= currRowEnd; ++row) {
const val = grid[row][currColEnd];
vals.push(val);
}
--currColEnd;
// Bottom
for (let col = currColEnd; col >= currColStart; --col) {
const val = grid[currRowEnd][col];
vals.push(val);
}
--currRowEnd;
// Left
for (let row = currRowEnd; row >= currRowStart; --row) {
const val = grid[row][currColStart];
vals.push(val);
}
++currColStart;
const size = vals.length;
const remK = k % size;
const movedVals = [];
for (let i = 0; i < size; ++i) {
const movedIdx = (i + remK) % size;
movedVals[i] = vals[movedIdx];
}
let i = 0;
currRowStart = startRow;
currRowEnd = endRow;
currColStart = startCol;
currColEnd = endCol;
// Top
for (let col = currColStart; col <= currColEnd; ++col) {
grid[currRowStart][col] = movedVals[i++];
}
++currRowStart;
// Right
for (let row = currRowStart; row <= currRowEnd; ++row) {
grid[row][currColEnd] = movedVals[i++];
}
--currColEnd;
// Bottom
for (let col = currColEnd; col >= currColStart; --col) {
grid[currRowEnd][col] = movedVals[i++];
}
--currRowEnd;
// Left
for (let row = currRowEnd; row >= currRowStart; --row) {
grid[row][currColStart] = movedVals[i++];
}
++currColStart;
// update the boundaries for the next layer
startRow = currRowStart;
endRow = currRowEnd;
startCol = currColStart;
endCol = currColEnd;
}
return grid;
};