m == mat.length
n == mat[0].length
1 <= m <= 3
1 <= n <= 3
mat[i][j]
是 0 或 1 。
BFS, 代码来自花花leetcode https://mp.weixin.qq.com/s/cxr4xp8iBRN6T2kgxWVTrw
可以再尝试DFS;
class Solution { public: int minFlips(vector<vector<int>>& mat) { int m = mat.size(); int n= mat[0].size(); auto flip = [&](int &s, int x, int y){ if(x<0 || x>=n || y<0 || y>=m) return; s^=(1<<y*n+x); }; auto flipCell = [&](int s, int x, int y){ int t=s; flip(t,x,y); flip(t,x-1,y); flip(t,x+1,y); flip(t,x,y+1); flip(t,x,y-1); return t; }; int steps=0; queue<int> q; vector<int> seen(1<<(n*m)); int s=0; for(int y=0;y<m;++y) for(int x=0;x<n;++x) s|=(mat[y][x]<<(y*n+x)); if(s==0) return 0; q.push(s); seen[s]=1; while(!q.empty()){ int size=q.size(); while(size--){ int ss=q.front(); q.pop(); for(int y=0;y<m;++y) for(int x=0;x<n;++x){ int t=flipCell(ss,x,y); if(seen[t]) continue; if(t==0) return steps+1; seen[t]=1; q.push(t); } } ++steps; } return -1; } };