1
+ // Runtime: 58 ms (Top 33.33%) | Memory: 13.5 MB (Top 31.11%)
1
2
const vector<pair<int , int >> directions{{1 , 0 }, {0 , 1 }, {-1 , 0 }, {0 , -1 }};
2
3
3
4
class Solution
4
5
{
5
6
protected:
6
7
int n, m;
7
-
8
+
8
9
int whichLayer (int x, int y) {
9
10
if (x < 0 || y < 0 || x >= n || y >= m) return -1 ;
10
11
int i = min (x, n - x - 1 );
11
12
int j = min (y, m - y - 1 );
12
13
return min (i, j);
13
14
}
14
-
15
+
15
16
void nextPos (int x, int y, int dir, int & nx, int & ny) {
16
17
nx = x + directions[dir].first ;
17
18
ny = y + directions[dir].second ;
18
19
}
19
-
20
- // Go to next position in the current layer (in clockwise order)
20
+
21
+ // Go to next position in the current layer (in clockwise order)
21
22
void advancePosition (int & x, int & y, int & d) {
22
23
int nx, ny;
23
24
nextPos (x, y, d, nx, ny);
@@ -28,43 +29,43 @@ class Solution
28
29
}
29
30
x = nx; y = ny;
30
31
}
31
-
32
+
32
33
public:
33
34
vector<vector<int >> rotateGrid (vector<vector<int >>& grid, int k)
34
- {
35
+ {
35
36
// Check validity of the arguments
36
37
if (grid.empty ()) throw invalid_argument (" empty grid" );
37
38
m = grid.size ();
38
39
n = grid[0 ].size ();
39
40
if (n == 0 ) throw invalid_argument (" empty grid" );
40
41
if (k < 0 ) throw invalid_argument (" negative k not accepted" );
41
-
42
+
42
43
// Trivial case
43
44
if (k == 0 ) return grid;
44
-
45
+
45
46
const int L = min (n, m) / 2 ;
46
47
for (int l = 0 ; l < L; l++) {
47
48
vector<int > v;
48
-
49
+
49
50
// Flatten a layer from grid into a vector
50
- int j = l, i = l; // start position
51
- int d = 0 ; // direction
51
+ int j = l, i = l; // start position
52
+ int d = 0 ; // direction
52
53
do {
53
54
v.push_back (grid[j][i]);
54
55
advancePosition (i, j, d);
55
- } while (!(i == l && j == l)); // until the start position is reached
56
-
56
+ } while (!(i == l && j == l)); // until the start position is reached
57
+
57
58
// Unflatten rotated vector back into the grid
58
- j = l; i = l; // start position
59
- d = 0 ; // direction
59
+ j = l; i = l; // start position
60
+ d = 0 ; // direction
60
61
int off = k % v.size ();
61
62
do {
62
63
grid[j][i] = v[off];
63
- off = (off + 1 ) % v.size ();
64
+ off = (off + 1 ) % v.size ();
64
65
advancePosition (i, j, d);
65
- } while (!(i == l && j == l)); // until the start position is reached
66
+ } while (!(i == l && j == l)); // until the start position is reached
66
67
}
67
-
68
+
68
69
return grid;
69
70
}
70
- };
71
+ };
0 commit comments