Question:
Framed matrix example:
The elements marked with the letter C indicate an internal matrix.
The elements marked with the letter B constitute a peripheral frame for the matrix whose members are marked with the letter C, and the elements marked with the letter A constitute a peripheral frame for the matrix whose elements are marked with the letters B and C.
A matrix will be called a "framed matrix" if all its elements that are marked with the same letter (A, B, C, and further) contain identical values. A generic normal framed matrix can be of any size.
Example for a framed matrix with numeric values:
I need to write a java function that receives a matrix as an argument, returns true if the matrix is framed and false if not.
thanks for your help
I wrote a function that returns true if the outer layer contains identical values (the first and last rows, and the first and last columns), I need to check the inner layers as well.
that's my partial solution:
public static boolean isFrameMatrix(int matrix[][])
{
int A = matrix[0][0];
int rows = matrix.length;
int cols = matrix[0].length;
int i=0 ,j = 0;
//Check the first and last rows
for(j=0; j<cols; j++)
{
if(A != matrix[0][j] || A != matrix[rows-1][j]) return false;
}
//Check the first and last columns
for(i = 0; i<rows; i++)
{
if(matrix[i][0] != A || matrix[i][cols-1] != A) return false;
}
return true;
}
Where in your current code you use index 0
or rows-1
(or cols-1
), use an expression that takes into account at which frame you are looking. The number of frames is determined by the minimum of the width and height of the matrix, and half of that (rounded upwards). For instance, a 5x7 matrix has (5+1)/2 frames, i.e. 3
Here is how you can achieve that:
public boolean isFrameMatrix(int[][] matrix) {
int height = matrix.length;
int width = matrix[0].length;
for (int frame = (Math.min(width, height) + 1) / 2; frame >= 0; frame--) {
int value = matrix[frame][frame];
for (int col = frame + 1; col < width - frame; col++) {
if (matrix[frame][col] != value ||
matrix[height - 1 - frame][col] != value) {
return false;
}
}
for (int row = frame + 1; row < height - frame; row++) {
if (matrix[row][frame] != value ||
matrix[row][width - 1 - frame] != value) {
return false;
}
}
}
return true;
}