![]() |
VOOZH | about |
Given a binary matrix of size M*N containing only 0 and 1. The task is to count the number of mappings in the matrix. There is one mapping between any two 1s if the following conditions are satisfied:
Examples:
Input: matrix[][] = { {0, 1, 1, 0, 0, 1},
{0, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 0, 0},
{0, 0, 1, 0, 0, 0} };
Output: 8
Explanation: Between each of the following 1s, there is one mapping. In total, there are 8 mappings:
matrix[0][1] -> matrix[2][1]
matrix[0][1] -> matrix[2][3]
matrix[0][2] -> matrix[2][1]
matrix[0][2] -> matrix[2][3]
matrix[0][5] -> matrix[2][1]
matrix[0][5] -> matrix[2][3]
matrix[2][1] -> matrix[3][2]
matrix[2][3] -> matrix[3][2]
Note that there is no mapping between any 1 on the 0th row with any on the 3rd row.
This is because the 2nd row contains 1s, which breaks the second condition.Input: matrix = { {0, 0, 0},
{1, 1, 1},
{0, 0, 0} };
Output: 0
Explanation: There does not exist two 1s located on two different rows.
Approach: The idea is to traverse each row and count the number of 1s in it. Traverse the subsequent rows and stop when the first next row contains at least one 1 in it. Compute the number of mappings between these two rows and add to the sum variable. Again repeat this process by making the latest row as starting reference point. Follow the steps below to solve the given problem.
Below is the implementation of the above approach.
8
Time complexity: O(M*N)
Auxiliary Space: O(1)