1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
问题:
给定m*n由0和1构成的二维数组,
对其中某个元素进行反转flip:0->1 or 1->0
那么其相邻的元素也会相应发生反转。
求,最终使得二维数组全为0需要最少几步?
若不能做到,返回-1。
Example 1: 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: Input: mat = [[0]] Output: 0 Explanation: Given matrix is a zero matrix. We don't need to change it. Example 3: Input: mat = [[1,1,1],[1,0,1],[0,0,0]] Output: 6 Example 4: Input: mat = [[1,0,0],[1,0,0]] Output: -1 Explanation: Given matrix can't be a zero matrix Constraints: m == mat.length n == mat[0].length 1 <= m <= 3 1 <= n <= 3 mat[i][j] is 0 or 1.
example 1:
解法:BFS + bitset
- 状态:当前的数组状况,使用bitset进行记录。
- visited:记录bitset->string:省略比较方法==
- 选择:
- 对所有cell,尝试反转。若已存在于visited的状态,不再加入queue。
bitset:
- 构造体:bitset<n> :⚠️ 注意:n必须为常数,不能为变量。
- 默认初始化为全 0。
- 方法:
- count:统计 1 的个数。
- flip(index):对第index位进行反转(index:0~n-1,从右向左 👈 )
- set(index):默认:对第index位置 1。
- set(index, 0):对第index位置 0。
- to_string:转化为字符串。
代码参考:
1 class Solution { 2 public: 3 int m,n; 4 int dir[5] = {1,0,-1,0,1}; 5 bitset<9> getstate(bitset<9>& state, int i, int j) { 6 bitset<9> next = state; 7 //vector<vector<int>> memo; 8 next.flip(i*m+j); 9 for(int d=1; d<5; d++) { 10 int x = i+dir[d-1]; 11 int y = j+dir[d]; 12 if(x<0 || y<0 || x>=n || y>=m) continue; 13 next.flip(x*m+y); 14 //memo.push_back({x,y}); 15 } 16 // if(next.count()==0) { 17 // cout<<"state:"<<state.to_string()<<endl; 18 // cout<<"i: "<<i<<" ; j: "<<j<<endl; 19 // cout<<"flip:"<<endl; 20 // for(auto m:memo) cout<<"x:"<<m[0]<<", y:"<<m[1]<<endl; 21 // } 22 return next; 23 } 24 int minFlips(vector<vector<int>>& mat) { 25 n=mat.size(); 26 m=mat[0].size(); 27 bitset<9> state; 28 int step = 0; 29 for(int i=0; i<n; i++) { 30 for(int j=0; j<m; j++) { 31 if(mat[i][j]) state.set(i*m+j); 32 } 33 } 34 //cout<<"START:"<<state.to_string()<<endl; 35 queue<bitset<9>> q; 36 unordered_set<string> visited; 37 if(state.count()==0) return 0; 38 q.push(state); 39 visited.insert(state.to_string()); 40 while(!q.empty()) { 41 int sz = q.size(); 42 for(int k=0; k<sz; k++) { 43 auto cur = q.front(); 44 q.pop(); 45 //cout<<"pop:"<<cur.to_string()<<endl; 46 if(cur.count()==0) return step; 47 for(int i=0; i<n; i++) { 48 for(int j=0; j<m; j++) { 49 auto next = getstate(cur, i, j); 50 if(visited.insert(next.to_string()).second) { 51 q.push(next); 52 //cout<<"push:"<<next.to_string()<<endl; 53 } 54 } 55 } 56 } 57 step++; 58 } 59 return -1; 60 } 61 };