標籤:acm dfs
| Time Limit: 1000MS |
|
Memory Limit: 65536K |
| Total Submissions: 16202 |
|
Accepted: 4349 |
Description
Given a
M×
N matrix
A.
Aij ∈ {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 30 1 00 0 11 0 04 40 0 0 11 0 0 01 1 0 10 1 0 0
Sample Output
Yes, I found itIt is impossible
Source
POJ Monthly Contest - 2009.08.23, MasterLuo題意為:
給定由01構成的矩陣,問能不能選出幾行構成新矩陣,使得新矩陣每列有且只有一個1.
枚舉所有行,行號遞增,判斷每行是否可以選(是否與前面所選的行發生衝突),當前行可選時,第j列如果為1,則用vis[j]=1標記,當行號>n(行數)時,判斷每列是否都有1.
#include <iostream>#include <stdio.h>#include <string.h>const int maxn=18;const int maxm=310;int mp[maxn][maxm];bool vis[maxm];int n,m;bool yes;using namespace std;bool row_ok(int rth)//rth為行號,判斷第rth行可以選{ for(int j=1;j<=m;++j) if(vis[j]&&mp[rth][j])//第j列已經有1了 return false; for(int j=1;j<=m;++j)//可以選 if(mp[rth][j]) vis[j]=true; return true;}bool judge()//當選的行號大於n時,判斷一下是不是每列都有1{ for(int j=1;j<=m;++j) if(!vis[j]) return false; return true;}void dfs(int rth){ if(rth>n+1)//因為當rth=n+1時,還需要判斷judge() return; if(judge())//注意這兩個if { yes=1; return; } for(int i=rth;i<=n&&!yes;++i) { if(row_ok(i)) { dfs(i+1);//注意這裡不是dfs(step+1),選的行號是遞增的 for(int j=1;j<=m;++j)//還原 if(mp[i][j]) vis[j]=0; } }}int main(){ while(scanf("%d%d",&n,&m)!=EOF) { for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) scanf("%d",&mp[i][j]); memset(vis,0,sizeof(vis)); yes=0; dfs(1); if(yes) printf("Yes, I found it\n"); if(!yes) printf("It is impossible\n"); } return 0;}
[ACM] POJ 3740 Easy Finding (DFS)