You are given an n x n 2D
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
matrix
representing an image, rotate the image by 90 degrees (clockwise).You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Approach
Java
import java.util.Arrays;public class RotateImage {public static void main(String[] args) {int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };rotate(matrix);System.out.println(Arrays.deepToString(matrix));}// function to rotate the imagestatic void rotate(int[][] matrix) {int n = matrix.length;for (int i = 0; i < n - 1; i++) {for (int j = i + 1; j < n; j++) {int tm = matrix[i][j];matrix[i][j] = matrix[j][i];matrix[j][i] = tm;}}for (int i = 0; i < n; i++) {int start = 0;int end = n - 1;while (start <= end) {{int tm = matrix[i][end];matrix[i][end] = matrix[i][start];matrix[i][start] = tm;}start++;end--;}}}}
C++
#include <bits/stdc++.h>using namespace std;//function to rotate the imagevoid rotate(vector<vector<int>> &matrix){int n = matrix.size();for (int i = 0; i < n - 1; i++){for (int j = i + 1; j < n; j++)swap(matrix[i][j], matrix[j][i]);}for (int i = 0; i < n; i++){int start = 0;int end = n - 1;while (start <= end){swap(matrix[i][end], matrix[i][start]);start++;end--;}}}int main(){vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};rotate(matrix);cout << "[";for (int i = 0; i < matrix.size(); i++){cout << "[";for (int j = 0; j < matrix[i].size(); j++){cout << matrix[i][j];if (j != matrix[i].size() - 1)cout << ",";}cout << "]";if (i != matrix.size() - 1)cout << ",";}cout << "]";return 0;}
No comments:
Post a Comment