650. Minimum Number of Flips to Convert Binary Matrix to Zero

MediumStackQueueBFSBitmask

Given a binary matrix mat, one flip toggles a chosen cell and its four direct neighbors. Return the minimum number of flips to turn the whole matrix into zeros, or -1 if impossible. The input is JSON {mat}.

Input: JSON {mat}.

Output: Integer — the minimum flips, or -1.

Examples

Example 1
Input: {"mat":[[0,0],[0,1]]}
Output: 3
Explanation: Three flips clear the matrix.
Example 2
Input: {"mat":[[0]]}
Output: 0
Explanation: Already zero.
Example 3
Input: {"mat":[[1,0,0],[1,0,0]]}
Output: -1
Explanation: Cannot be cleared.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →