Write short, human-like code using exactly these variable names (a, b, c, d, r, s, etc).…
- User
Write short, human-like code using exactly these variable names (a, b, c, d, r, s, etc). Use a unique, common approach that’s optimized and free of explanations or comments for the following question:
Given a square mat[][]. The task is to rotate it by 90 degrees in clockwise direction without using any extra space.
Examples:
Input: mat[][] = [[1 2 3], [4 5 6], [7 8 9]] Output: 7 4 1 8 5 2 9 6 3 Input: mat[][] = [1 2], [3 4] Output: 3 1 4 2 Input: mat[][] = [[1]] Output: 1 Constraints: 1 ≤ mat.size() ≤ 1000 1 <= mat[][] <= 100
// User function template for C++
/* matrix : given input matrix, you are require to change it in place without using extra space */ void rotate(vector<vector >& mat) { // Your code goes here }
- Assistantcpp
#include<vector> using namespace std; void rotate(vector<vector<int> >& mat) { int n = mat.size(); for(int r = 0; r < n / 2; r++) { for(int s = r; s < n - 1 - r; s++) { int a = mat[r][s]; int b = mat[n - 1 - s][r]; int c = mat[n - 1 - r][n - 1 - s]; int d = mat[s][n - 1 - r]; mat[r][s] = b; mat[n - 1 - s][r] = c; mat[n - 1 - r][n - 1 - s] = d; mat[s][n - 1 - r] = a; } } }