VOOZH about

URL: https://www.geeksforgeeks.org/dsa/total-coverage-zeros-binary-matrix/

⇱ Total coverage of all zeros in a binary matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Total coverage of all zeros in a binary matrix

Last Updated : 17 May, 2026

Given a binary matrix that contains only 0s and 1s, find the sum of coverage of all zeros in the matrix, where coverage for a particular 0 is defined as the number of directions (left, right, up, and down) in which at least one 1 is present before reaching the matrix boundary.
While moving in a direction, once a 1 is encountered, count it only once for that direction.

Examples:

Input : [1, 1, 1, 0
1, 0, 0, 1]

Output : 8
Explanation: Coverage of first zero is 2 Coverages of other two zeros is 3 Total coverage = 2 + 3 + 3 = 8

👁 2056958046


Input :[0, 0, 0, 0
1, 0, 0, 1
0, 1, 1, 0
0, 1, 0, 0]
Output : 20
Explanation: First four zeros are surrounded by only one 1. So coverage for zeros in first row is 1 + 1 + 1 + 1 Zeros in second row are surrounded bythree 1's. Note that there is no 1 above. There are 1's in all other three directions.Coverage of zeros in second row = 3 + 3. Similarly counting for others also, we getoverall count as below.1 + 1 + 1 + 1 + 3 + 3 + 2 + 2 + 2 + 2 + 2 = 20

[Naive Approach] Using Directional Traversal – O(r * c * (r + c)) Time and O(1) Space

The idea is to examine every 0 cell in the matrix and check in all four directions (left, right, up, down) to see whether there exists a 1. For each direction, we keep moving until either a 1 is found or the boundary is reached. Every successful direction contributes 1 to the total coverage count.

  • Traverse every cell of the matrix
  • For each 0 cell, scan left, right, upward, and downward directions
  • If a 1 is found in a direction, increase the coverage count
  • Return the total accumulated coverage

Output
20

[Efficient Approach] Using Four Direction Traversals – O(r * c) Time and O(1) Space

The idea is to avoid scanning entire rows and columns repeatedly for every 0 cell. Instead, we traverse rows and columns in both directions while keeping track of whether a 1 has been seen. Whenever a 0 cell is encountered after seeing a 1 in that direction, its coverage count increases. By processing left-to-right, right-to-left, top-to-bottom, and bottom-to-top separately, we efficiently compute total coverage.

  • Traverse each row from left to right and right to left while tracking presence of 1
  • Increase coverage whenever a 0 cell is found after a 1 in current direction
  • Repeat the same process for each column from top to bottom and bottom to top
  • Return the total accumulated coverage count

Output
20
Comment
Article Tags:
Article Tags: