深度优先搜索
Posted zhulmz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深度优先搜索相关的知识,希望对你有一定的参考价值。
深度优先搜索
基本原理:
从一个状态开始不断转移,直至无法转移,然后退回前一步的状态,继续转移到其他状态,知道求解
基本思想:递归
例一:
给定整数a1,a2,a3......an,判断是否可以从中选出若干数,使们的和恰好为K;
#include<iostream>
using namespace std;
int a[100];
bool dfs(int i, int sum, int n, int k)
{
if(i == n )
return sum == k;
if(dfs(i + 1, sum , n, k))
return true;
if(dfs(i + 1, sum + a[i], n, k))
return true;
return false;
}
int main()
{
int n, k;
cin >> n >> k;
for(int i = 0; i < n; i++){
cin >> a[i];
}
bool t = dfs(0, 0, n, k);
if(t == true)
cout << "YES";
else
cout << "NO";
return 0;
}
例二:
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 Input
10 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
思路:运用深度优先搜索的方法,首先确定一个w,将其相邻的w都变成‘.’,这样,每调用一次dfs函数,就会消去一处水洼,dfs函数的执行次数就是水洼数;
#include<iostream>
using namespace std;
int N, M;
char field[100][100];
void dfs(int x, int y)
{
field[x][y] = '.';
//两层循环,依次遍历与该点相邻的点
for(int dx = -1; dx <= 1; dx++){
for(int dy = -1; dy <= 1; dy++){
int nx = x + dx, ny = y + dy;
if(nx >= 0 && nx < N && ny >= 0 && ny < M && field[nx][ny] == 'w')
dfs(nx, ny);
}
}
}
int main()
{
cin >> N >> M;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cin >> field[i][j];
}
}
int sum = 0;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if(field[i][j] == 'w')
{
dfs(i,j);
sum++;
}
}
}
cout << sum << endl;
return 0;
}
以上是关于深度优先搜索的主要内容,如果未能解决你的问题,请参考以下文章