poj 3740 -- Easy Finding (dfs)

Easy Finding
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 16787   Accepted: 4548

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 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

 

 

题目大意:给出一个m行n列的数组,元素只有0和1,

问:能不能找出几行,使得每一列都有且仅有一个1.

 

分析:直接深搜即可

 

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 
 5 int vis[311];//记录该列有1没
 6 int n, m;
 7 int a[20][311];
 8 bool flag;
 9 
10 bool fuhe(int i){
11     for (int j = 1; j <= n; j++)
12         if (a[i][j] && vis[j])
13             return false;
14     return true;
15 }
16 
17 bool manzu(){//判断是否每一列都有且仅有一个1
18     for (int j = 1; j <= n; j++)
19         if (!vis[j])
20             return false;
21     return true;
22 }
23 
24 int dfs(int ans){
25     int i, j;
26     if (ans > m+1)//注意遍历>m时还要判断manzu(),所以应该是超过m+1时才返回
27         return false;
28     if (manzu()){//每一列都有且仅有一个1
29         flag = true;
30         return true;
31     }
32     if (fuhe(ans)){//该行目前看来符合要求
33         for (j = 1; j <= n; j++)
34             if (a[ans][j])//将该行有1的列全部都设为vis[j]=true;
35                 vis[j] = 1;
36         for (j = ans; j <= m&&!flag; j++){//按行的先后dfs的,小于i行的之前已dfs
37             if (dfs(j + 1))//接下来的全部ok,就可以返回true了
38                 return true;
39         }
40         //遍历了ans+1到n之后都不行,则该行不行,告诉上一层,回溯
41         for (j = 1; j <= n; j++)
42             if (a[ans][j])//回溯之前记住要还原
43                 vis[j] = 0;
44         return false;
45         }
46 }
47 
48 int main()
49 {
50     while (scanf("%d%d", &m, &n) != EOF){
51         int i, j;
52         for (i = 1; i <= m; i++)
53             for (j = 1; j <= n; j++)
54                 scanf("%d",&a[i][j]);
55         memset(vis, 0, sizeof(vis));
56         flag = false;
57         for (i = 1; i <= m; i++){
58             if (dfs(i))
59                 break;
60         }
61         if (flag)
62             printf("Yes, I found it\n");
63         else
64             printf("It is impossible\n");
65     }
66     return 0;
67 }

 

posted on 2015-04-07 01:04  龙息之断  阅读(182)  评论(0)    收藏  举报

导航