Learn-dsa..in 30 days!



























CC-13 : Matrix shift upwards row wise.

Description:

Given input matrix mat, shift the rows upwards. The first row should rotate to last row.

Test cases and expected outputs:

Input Expected outputs
mat = {
{7,1,4,1},
{9,9,3,0},
{2,1,4,3},
{6,2,7,9}};
9,9,3,0,
2,1,4,3,
6,2,7,9,
7,1,4,1,
mat = {
{3,1,2,6,7},
{9,3,2,7,1},
{1,0,0,9,3},
{0,3,6,9,2},
{7,2,4,9,1}};
9,3,2,7,1,
1,0,0,9,3,
0,3,6,9,2,
7,2,4,9,1,
3,1,2,6,7,
mat = {
{4,1,7,9,7},
{2,3,6,7,8},};
2,3,6,7,8,
4,1,7,9,7,

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Initialize an integer array firstRow with same length as number of columns in mat.
Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
If we iterating through the first row, set firstRow[cIdx]=mat[rIdx][cIdx], this will load first row elements into firstRow array.
If we are iterating through the last row, set mat[rIdx][cIdx]=firstRow[cIdx]; this will load first row elements into the last row.
If we are iterating through any other row, set mat[rIdx][cIdx]=mat[rIdx+1][cIdx]; this will shift elements of this row upwards by one row.
After above loops have completed, return mat as the rows have been shifted upwards by one row.

Code:

public int[][] matShiftUpwardRowwise(int[][] mat) throws Exception{
	int[] firstRow=new int[mat[0].length];
	for (int rIdx=0; rIdx < mat.length; rIdx++) {
		for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
			if (rIdx==0) {
				firstRow[cIdx]=mat[rIdx][cIdx];
			}
			if (rIdx==mat.length-1) {
				mat[rIdx][cIdx]=firstRow[cIdx];
			}else {
				mat[rIdx][cIdx]=mat[rIdx+1][cIdx];
			}			
		}
	}
	
	return mat;
}

Click here to download and run code and test cases !