Reshape the Matrix in java

In MATLAB, there is a very useful function called “reshape”, which can reshape a matrix into a new one with different size but keep its original data.

You are given a matrix represented by a two-dimensional array (m*n), and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the “reshape” operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output “Not possible to reshape.”

Input Format

The input given is going to be row count(m) and column count(n) in first row and then m more rows with n values each (the actual matrix) and then the new row count and column count in the last row (the size to which you need to reshape the matrix)

Output Format

The reshaped matrix should be printed as given in the input, If it is not possible to reshape the matrix, print “Not possible to reshape.”

Example 1

Input

2 2
1 2
3 4
1 4

Output

1 2 3 4

Explanation

The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2

Input

2 2
1 2
3 4
2 4

Output

Not possible to reshape.

Explanation

There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output “Not possible to reshape.”

r,c <100

Solution of Reshape the Matrix in java:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();

int mat[][]=new int[m][n];
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
mat[i][j]=sc.nextInt();
}
}

int r=sc.nextInt();
int c=sc.nextInt();
int[][] trans=new int[r][c];

int k=0, l=0;
if(r*c!=m*n)
{
System.out.println("Not possible to reshape.");
}
else
{
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
trans[k][l++]= mat[i][j];
if(l==c)
{
k++;
l=0;
}
}
}

for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
System.out.print(trans[i][j] + " " );
}
System.out.println();
}
}
}
}