c++ solution (3 ms)


  • 0
    class Solution {
    public:
      void move(int s, vector<vector<int>>& matrix) {
        int pr = matrix[s][s], n = matrix.size();
        for (int i = s + 1; i < n - s; ++i) swap(pr, matrix[s][i]);
        for (int i = s + 1; i < n - s; ++i) swap(pr, matrix[i][n - 1 - s]);
        for (int i = n - 2 - s; i >= 0 + s; --i) swap(pr, matrix[n - 1 - s][i]);
        for (int i = n - 2 - s; i >= 0 + s; --i) swap(pr, matrix[i][s]);
      }
      void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        if (n < 2) return;
        for (int s = 0; s < n / 2; ++s) {
          int num_move = n - 1 - s * 2;
          while (num_move) {
            move(s, matrix);
            num_move--;
          }
        }
      }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.