题目链接
题解:这题跑一下bfs就好了,用一个数x表示此时n盏灯的状态,二进制为 1 表示灯开。所以最后只要判断x为0,所有灯就关了。
#include<bits/stdc++.h>
using namespace std;
const int M = (1 << 11);
struct node{
int pre, step;
};
int mp[110][110], vis[M];
int n, m, mx;
void bfs(){
queue<node>q;
q.push(node{mx, 0});
vis[mx] = 1;
while(!q.empty()){
node t = q.front();
q.pop();
for(int i = 1; i <= m; ++i){
int now = t.pre;
for(int j = 1; j <= n; ++j){
if(mp[i][j] == 1){
if((now>>(j - 1)) & 1) // 判断这一位是否为1
now = now ^ (1<<(j - 1)); // 变成 0
}
else if(mp[i][j] == -1)
now = now | (1<<(j - 1)); // 变成1
}
if(now == 0){
cout<<t.step + 1<<endl;
vis[now] = 1;
return;
}
if(vis[now]) continue;
q.push(node{now, t.step + 1});
vis[now] = 1;
}
}
}
int main()
{
cin>>n>>m;
for(int i = 1; i <= m; ++i)
for(int j = 1; j <= n; ++j)
scanf("%d", &mp[i][j]);
mx = (1<<n) - 1;
bfs();
if(!vis[0]) puts("-1");
}