Given an M × N matrix of integers whose each cell can contain a negative, zero, or a positive value, determine the minimum number of passes required to convert all negative values in the matrix positive.

Only a non-zero positive value at cell (i, j) can convert negative values present at its adjacent cells (i-1, j), (i+1, j), (i, j-1), and (i, j+1), i.e., up, down, left and right.

 
For example, the following matrix needs 3 passes, as demonstrated:

 
A Simple Matrix
 

Practice this problem

 
The idea is to use Breadth–first Search as it is the shortest path problem. The algorithm can be implemented as follows:

  1. Create a queue Q and enqueue cell coordinates of all positive numbers in the matrix. Create another queue q to separate the positive numbers involved in the previous pass from the positive numbers in the current pass.
  2. Do till first queue Q is empty
    1. Copy contents of the original queue Q to the second queue q and empty the original queue.
    2. Do till second queue q is empty
      1. Remove the front node from queue q and check all four adjacent cells of the current cell.
      2. If any of the four adjacent cells is negative, make its value positive and enqueue it into queue Q.
    3. Increment number of passes by 1.
  3. If all the nodes in the queue are processed, return the total number of passes.

We can find all the adjacent cells of the given cell by storing the relative position of movement from any cell in an array. For example, if the current cell is (x, y), we can move to (x + row[k], y + col[k]) cell for 0 <= k < 4 using the following arrays:

row[] = { -1, 0, 0, 1 }
col[] = { 0, -1, 1, 0 }
 
So, from any position (x, y), we can move to:
 
(x – 1, y)
(x, y – 1)
(x, y + 1)
(x + 1, y)

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The total number of passes required is 3

Java


Download  Run Code

Output:

The total number of passes required is 3

Python


Download  Run Code

Output:

The total number of passes required is 3

The time complexity of the proposed solution is O(M × N) and requires O(M × N) extra space for queue data structure, where M and N are dimensions of the matrix.