Learn-dsa..in 30 days!



























CC-6 : Check if matrix is scalar matrix.

Description:

A matrix is a scalar matrix, if all elements of the diagonal are the same and all elements except the diagonal elements are 0. Given matrix mat, check if the matrix is a scalar matrix.

Test cases and expected outputs:

Input1 Expected outputs
mat = {
{3,0,0},
{0,3,0},
{0,0,3}}
The matrix is a Scalar Matrix.
mat= {
{55,0,0,0},
{0,55,0,0},
{0,0,55,0},
{0,0,55,55}}
The matrix is *not* a Scalar Matrix.
mat={
{30,40},
{50,30}}
The matrix is *not* a Scalar Matrix.

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Initialize int variable diag to mat[0][0].
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:
o 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:
Check if (rIdx==cIdx):
If mat[rIdx][cIdx] != diag, return false, exit program.
Check if (rIdx != cIdx):
If mat[rIdx][cIdx] != 0, return false, exit program.
If above loops are completed without intermediate return/exit, it means the input matrix is a scalar matrix so, return true.

Code:

public boolean  matArrayCheckScalar(int[][] mat) throws Exception{
	int diag=mat[0][0];
	for (int rIdx=0; rIdx < mat.length; rIdx++) {
		for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
			if (rIdx==cIdx) {
				if (mat[rIdx][cIdx] != diag) {
					return false;
				}
			}else {
				if (mat[rIdx][cIdx] != 0) {
					return false;
				}
			}
		}
	}
	return true;
}

Click here to download and run code and test cases !