LeetCode解题报告(459)-- 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
Posted onEdited onViews: Valine:
Problem
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
A binary matrix is a matrix with all cells equal to 0 or 1 only.
A zero matrix is a matrix with all cells equal to 0.
Example 1:
1 2 3
Input: mat = [[0,0],[0,1]] Output: 3 Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
Example 2:
1 2 3
Input: mat = [[0]] Output: 0 Explanation: Given matrix is a zero matrix. We do not need to change it.
Example 3:
1 2 3
Input: mat = [[1,0,0],[1,0,0]] Output: -1 Explanation: Given matrix cannot be a zero matrix.
classSolution { public: intminFlips(vector<vector<int>>& mat){ // from matrix to bitVec int bitVec = 0; m = mat.size(), n = mat[0].size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { bitVec <<= 1; bitVec |= mat[i][j]; } }
queue<int> q; unordered_set<int> visited; int step = 0; q.push(bitVec); visited.insert(bitVec); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; ++i) { int cur = q.front(); q.pop(); if (cur == 0) { return step; } // try every position for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int next = helper(i, j, cur); if (!visited.count(next)) { visited.insert(next); q.push(next); } } } } step++; } return-1; } private: int m, n; inthelper(int i, int j, int cur){ int dx[] = {-1, 0, 1, 0}; int dy[] = {0, -1, 0, 1}; // flip [i, j] int pos = m * n - 1 - i * n - j; cur ^= 1 << pos; // flip neighbors for (int k = 0; k < 4; ++k) { int newX = i + dx[k]; int newY = j + dy[k]; if (newX < 0 || newX >= m || newY < 0 || newY >= n) { continue; } pos = m * n - 1 - newX * n - newY; cur ^= 1 << pos; } return cur; } };