Problem
Given two matrices, write a function to check whether the two matrices are identical or not. Matrices are considered identical if all the elements in the respective positions of the two matrices are the same.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Iteration
To check if two matrices are identical, we need to compare their elements at each corresponding position. If every element matches, the matrices are identical. Otherwise, they are not. Additionally, we must ensure that the dimensions of the two matrices are the same before comparing their elements.
Here is the approach:
- Dimension Check: First, ensure both matrices have the same dimensions. If the number of rows or columns differ, they cannot be identical, and we can return
false
immediately. - Element-wise Comparison: If the dimensions match, iterate through each element of both matrices and compare them.
- Use nested loops to traverse each element.
- For each pair of corresponding elements, check if they are equal.
- If any pair is found to be different, return
false
.
- All Elements Matched: If all elements in respective positions are the same after traversal, return
true
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
, wherem
is the number of rows andn
is the number of columns. We traverse every element of both matrices. - 🧺 Space complexity:
O(1)