1+ // Runtime: 58 ms (Top 33.33%) | Memory: 13.5 MB (Top 31.11%)
12const vector<pair<int , int >> directions{{1 , 0 }, {0 , 1 }, {-1 , 0 }, {0 , -1 }};
23
34class Solution
45{
56protected:
67 int n, m;
7-
8+
89 int whichLayer (int x, int y) {
910 if (x < 0 || y < 0 || x >= n || y >= m) return -1 ;
1011 int i = min (x, n - x - 1 );
1112 int j = min (y, m - y - 1 );
1213 return min (i, j);
1314 }
14-
15+
1516 void nextPos (int x, int y, int dir, int & nx, int & ny) {
1617 nx = x + directions[dir].first ;
1718 ny = y + directions[dir].second ;
1819 }
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)
2122 void advancePosition (int & x, int & y, int & d) {
2223 int nx, ny;
2324 nextPos (x, y, d, nx, ny);
@@ -28,43 +29,43 @@ class Solution
2829 }
2930 x = nx; y = ny;
3031 }
31-
32+
3233public:
3334 vector<vector<int >> rotateGrid (vector<vector<int >>& grid, int k)
34- {
35+ {
3536 // Check validity of the arguments
3637 if (grid.empty ()) throw invalid_argument (" empty grid" );
3738 m = grid.size ();
3839 n = grid[0 ].size ();
3940 if (n == 0 ) throw invalid_argument (" empty grid" );
4041 if (k < 0 ) throw invalid_argument (" negative k not accepted" );
41-
42+
4243 // Trivial case
4344 if (k == 0 ) return grid;
44-
45+
4546 const int L = min (n, m) / 2 ;
4647 for (int l = 0 ; l < L; l++) {
4748 vector<int > v;
48-
49+
4950 // 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
5253 do {
5354 v.push_back (grid[j][i]);
5455 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+
5758 // 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
6061 int off = k % v.size ();
6162 do {
6263 grid[j][i] = v[off];
63- off = (off + 1 ) % v.size ();
64+ off = (off + 1 ) % v.size ();
6465 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
6667 }
67-
68+
6869 return grid;
6970 }
70- };
71+ };
0 commit comments