Description
Given a
M×
N matrix
A.
A
ij ∈ {0, 1} (0 ≤ i < M, 0 ≤ j < N), could you find some rows that let every cloumn contains and only contains one 1.
Input
There are multiple cases ended by
EOF. Test case up to 500.The first line of input is
M,
N (
M ≤ 16,
N ≤ 300). The next
M lines every line contains
N integers separated by space.
Output
For each test case, if you could find it output "Yes, I found it", otherwise output "It is impossible" per line.
Sample Input
3 3 0 1 0 0 0 1 1 0 0 4 4 0 0 0 1 1 0 0 0 1 1 0 1 0 1 0 0
Sample Output
Yes, I found it It is impossible
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn=500; bool mark[maxn]; int vis[maxn][maxn]; int m,n; bool ans; void dfs(int c) { int count=0; for(int i=1;i<=m;i++) { if(mark[i]&&vis[i][c]) count++; } if(count>1) return; if(count==1) { if(c<n) dfs(c+1); else { ans=true; return ; } } if(count==0) { for(int i=1;i<=m;i++) { bool work=true; if(!mark[i]&&vis[i][c]) { for(int j=1;j<c;j++) { if(vis[i][j]) { work=false; break; } } if(work) { mark[i]=true; if(c<n) dfs(c+1); else ans=true; mark[i]=false; } } } } } int main() { int a; while(scanf("%d%d",&m,&n)!=EOF) { memset(vis,0,sizeof(vis)); memset(mark,0,sizeof(mark)); for(int i=1;i<=m;i++) { for(int j=1;j<=n;j++) { scanf("%d",&a); vis[i][j]=a==1; } } ans=false; dfs(1); if(ans) printf("Yes, I found it\n"); else printf("It is impossible\n"); } return 0; }