8. Rotate Matrix by 90 degree

8. Rotate Matrix by 90o


Problem link :- click here


package progams;

import java.util.Scanner;

public class Matrix__8
{

	/*
	    Given a square matrix, we have to turn it by 90 degrees 
	    		Input 				Output
	    			1   2   3				7   4   1
	    			4   5   6				8   5   2
	    			7   8   9				9   6   3
	    		
	    we know how to transpose a matrix          mat[i][j]  =  mat[j][i]
	    		Transpose
	    			1   4   7
	    			2   5   8
	    			3   6   9
	    			
	    		we are one step away from the output. If we interchange the columns 
	    		(left columns by right columns)
													mat[i][j]  =  mat[i][(n-1)-j]
	*/
	
	static void rotateMatrixBy90(int mat[][], int n)
	{
		//while transposing we should traverse through either upper triangle or lower triangle
		//or else we will get the same matrix
		for(int i=0; i<n; i++)
		{
			// by taking       j=i     we taking only upper triangle 
			for(int j=i+1; j<n; j++)
			{
				int temp = mat[i][j];
				mat[i][j] = mat[j][i];
				mat[j][i] = temp;
			}
		}
		
		//interchanging the columns
		for(int i=0; i<n; i++)
		{
			//if '0' is the first then '(n-1)' is the last column
			//if  'j' is the first then '(n-1) - j' is the last column
			for(int j=0; j<n/2; j++)
			{
				int temp =  mat[i][j];
				mat[i][j] = mat[i][(n-1)-j];
				mat[i][(n-1)-j] = temp;
			}
		}
	}
	
	
	public static void main(String[] args)
	{
		int i, j, r, c;
		
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the number of rows : ");
		r = s.nextInt();
		System.out.print("Enter the numvber of columns : ");
		c = s.nextInt();
		int matrix[][] = new int[r][c];
		System.out.println("Enter the elements of the matrix : ");
		for(i=0; i<r; i++)
		{
			for(j=0; j<c; j++)
				matrix[i][j] = s.nextInt();
		}
		System.out.println("Given matrix : ");
		printMatrix(matrix, r, c);

		rotateMatrixBy90(matrix, c);
		System.out.println("\n\nMatrix after rotating by 90 dgrees : ");
		printMatrix(matrix, r, c);
	}

	static void printMatrix(int mat[][], int r, int c)
	{
		for(int i=0; i<r; i++)
		{
			for(int j=0; j<c; j++)
				System.out.print(mat[i][j] + "  ");
			System.out.println();
		}
	}
}

Time complexity :- O(n2)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree