Given a matrix, check if it’s an identity matrix.
Example 1:
{{1,0,0},
{0,1,0},
{0,0,1}}
The matrix above is an identity matrix.
Example 2:
{{1,4,3},
{9,1,0},
{0,0,1}}
The matrix above is not an identity matrix.
A matrix is called an identity matrix or a unit matrix if the ones
and other elements in the matrix are zero
.
For example:
{{1,0,0},
{0,1,0},
{0,0,1}}
The example above is a 3x3
identity matrix.
one
.zero
.false
, then the matrix is not an identity matrix. Return false
.true
, indicating that the matrix is an identity matrix.public class Main{private static boolean checkIdentityMatrix(int[][] matrix){for(int i=0; i<matrix.length;i++)for(int j=0; j<matrix[i].length;j++){if((i == j && matrix[i][j] != 1) || (i != j && matrix[i][j] != 0)) return false;}return true;}public static void main(String[] args){int[][] matrix = {{1,0,0},{0,1,9},{0,0,1}};if(checkIdentityMatrix(matrix)) System.out.println("The matrix is an identity matrix");else System.out.println("The matrix is not an identity matrix");}}
In the code above, we check if the following matrix is an identity matrix.
{{1,0,0},
{0,1,9},
{0,0,1}}
As the element at the second row and third column is not zero, it’s not an identity matrix.