Discussion About Rotate Image!

This is Discussion thread about Rotate Image!

1 Like

#include<bits/stdc++.h>
using namespace std;
//#define for(i,a,n) for (int i=a;i<n;i++)
typedef long long int lli;
typedef pair<int, int> pii;
typedef vector<pair<int, int> > vii;
typedef vector vi;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);int arr[1001][1001];int n;
cin>>n;
for(int i=n-1;i>=0;i–)
{
for(int j=0;j<n;j++)
cin>>arr[j][i];
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<arr[i][j]<<" ";
cout<<endl;
}
return 0;
}
Why is this wrong?

u actually messed up the the loops at beginning it should be like this…

#include<iostream>
using namespace std;

int main(){
    int n;
    cin>>n;
    int a[n][n];
    for(int j=0;j<n;j++){
        for(int i=(n-1);i>=0;i--){
            cin>>a[i][j];
        }
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

Why i am getting TLE
It compiles successfully
But error in submitting the code

#include
#include

using namespace std;

void swap(int a,int b){
int temp=a;
a=b;
b=temp;
}

void rotate(int a[][5],int n){
for(int row=0;row<n;row++){
int start_col=0;
int end_col=n-1;
while(start_col<end_col){
swap(a[row][start_col],a[row][end_col]);
start_col++;
end_col–;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
while(i<j)
a[i][j]=a[j][i];
}
}
}

void display(int a[][5],int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<a[i][j]<<" “;
}
cout<<”\n";
}
}

int main() {
int arr[5][5],n;
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>arr[i][j];
rotate(arr,n);
display(arr,n);
return 0;
}

TLE often happens when you unnecessarily run a lot of loops instead of finding some common patterns. There is a hint for you, try finding the relation of the rotated array element positions and the original array element positions.

#include
using namespace std;
int main()
{
int n,m,i,j,A[10][10];
cout<<“enter the number of rows and columns”<<endl;
cin>>n>>m;
cout<<“enter the elements”<<endl;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cin>>A[i][j];
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cout<<A[i][j]<<" ";
cout<<endl;
}
for(int k=0;k<n;k++)
{
i=0;
j=m-1;
while(i<j)
{
swap(A[k][i],A[k][j]);
i++;
j–;

	}	

}
for(i=0;i<=n-1;i++)
{
for(j=0;j<=m-1;j++)
{
if(i<j)
swap(A[j][i],A[i][j]);
}
}
for( i=0;i<n;i++)
{
for(j=0;j<m;j++)
cout<<A[i][j]<<" ";
cout<<endl;
}
return 0;
}

only one test case is passed why ?

//This works fine !
#include
using namespace std;
int main() {
int N;
cin>>N;
int A[N][N];
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cin>>A[i][j];
}
}
for(int col=N-1;col>=0;col–){
for(int row=0;row<N;row++){
cout<<A[row][col]<<" ";
}
cout<<endl;
}
return 0;
}