DFS(深度优先搜索):从某个状态开始。不断地转移状态直到无法转移,然后回退到前一步的状态,继续转移到其他状态,如此不断重复,直到找到最终的解。根据深度优先搜索的特点,采用递归函数实现比较简单。———《挑战程序设计竞赛》
题目:1、部分和问题
给定整数a1、a2、…an,判断是否可以从中选出若干数,使它们的和恰好为K。
输入首先,n和k,n表示数的个数,k表示数的和。
接着一行n个数。
(1<=n<=20,保证不超int范围)输出如果和恰好可以为k,输出“YES”,并按输入顺序依次输出是由哪几个数的和组成,否则“NO”
样例输入
4 13
1 2 4 7
样例输出
YES
2 4 7
思路:本题需要减掉的是
1.从当前状态如何转移都不会存在解
2.当sum超过k时,也没必要继续搜索
#include<cstdio>
#define MAX_N 20
int a[MAX_N]={0};
int b[MAX_N]={0};
int k,n;
bool dfs(int i,int sum){
//返回sum是否与k相等
if( i==n ) return sum == k;
//不加上a[i]的情况
if( dfs( i+1 , sum ) ){
b[i]=0;
return true;
}
//加上a[i]的情况
if( dfs( i+1 , sum+a[i])){
b[i]=1;
return true;
}
return false;
}
int main(){
scanf("%d %d",&n,&k);
for( int i=0; i < n; i++ ){
scanf("%d",&a[i]);
}
if( dfs( 0,0 ) ){
printf("YES\n");
for(int i=0; i < n; i++){
if( b[i] ) printf("%d ",a[i]);
}printf("\n");
}else {
printf("NO\n");
}
return 0;
}
2、Lake Counting(POJ No.2386)
Description
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (’.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John’s field, determine how many ponds he has.
Input
-
Line 1: Two space-separated integers: N and M
-
Lines 2…N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
Output -
Line 1: The number of ponds in Farmer John’s field.
Sample Input10 12
W…WW.
.WWW…WWW
…WW…WW.
…WW.
…W…
…W…W…
.W.W…WW.
W.W.W…W.
.W.W…W.
…W…W.
Sample Output
3
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
C语言实现:
#include<stdio.h>
#define MAX_N 100
#define MAX_M 100
void solve();
void dfs(int x,int y);
int N=0,M=0;
char field[MAX_N][MAX_M+1];
int main(){
scanf("%d %d", &N, &M);
getchar();
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
scanf("%c", &field[i][j]);
}getchar();
}
solve();
return 0;
}
void dfs(int x,int y){
field[x][y]='.';
int nx,ny;
for (int dx = -1; dx<=1; dx++){
for(int dy = -1; dy<=1; dy++){
nx = x+dx,ny=y+dy;
if( nx >= 0 && nx < N && 0 <= ny && ny<=M && field[nx][ny] == 'W') dfs(nx,ny);
}
}
return ;
}
void solve(){
int res=0;
for( int i = 0; i < N; i++){
for( int j = 0; j < M ;j++){
if(field[i][j] == 'W'){
dfs(i,j);
res++;
}
}
}
printf("%d\n",res);
}
2019/9/1