关于深度优先遍历(DFS)

概念:深度优先搜索是搜索的手段之一,它从某个状态开始,不断地转移状态直到无法移动,然后再回退到前一步的状态,继续转移到其他状态,如此不断重复直到找到最终的解。(一条路走到黑不到黄河不死心,碰壁才回头。)

在这里插入图片描述

访问顺序如上图所示

例题如下:

部分和问题

**
描述
给定整数a1、a2、…an,判断是否可以从中选出若干数,使它们的和恰好为K。
输入
首先,n和k,n表示数的个数,k表示数的和。
接着一行n个数。(1<=n<=20,保证不超int范围)**

输出

如果和恰好可以为k,输出“YES”,并按输入顺序依次输出是由哪几个数的和组成,否则“NO”

解题思路:从a1开始,看之后的每个数加或不加,在全部数都决定后再判断和是否等于k即可。

代码如下:

#include<iostream>
using namespace std;
const int maxn = 25;
int a[maxn];
int n, k;
bool dfs(int i, int sum)
{

	if (i == n)return sum == k;

	if (dfs(i + 1, sum))
		return true;
	
	if (dfs(i + 1, sum + a[i]))
		return true;

	   return false;//如果加上a[i]和不加上a[i]都不满足则返回false
}


int main()
{
	while (cin >> n)
	{	
		for (int i = 0; i < n; i++)
		{
			cin >> a[i];
		}
		cin >> k;
		if (dfs(0, 0))
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
	}
	return 0;
}

运行结果如下:

在这里插入图片描述

还可以将最终结果记忆化:

#include<iostream>
using namespace std;
const int maxn = 25;
int a[maxn];
typedef long long LL;
int n, k;
int vis[maxn];
/*
4
1 2 4 7
13
*/
int flag,s=0;
void dfs(int m)
{
	

	if (s == k)
	{
		if (flag == 0)flag = 1;
			
		if (flag){
			cout << "Yes" << endl;
			for (int i = 0; i < n; i++)
			{		
				
				if (vis[i] == 1)
					cout << a[i]<<" ";
			}
			cout << endl;
		}
	}

	for (int i = m; i < n; i++)
	{
		s += a[i];//找到s+a[i]等于k的
		vis[i] = 1;
		dfs(i + 1);
		s -= a[i];//没找到就减去a[i],继续遍历
		vis[i] = 0;//并初始化访问
	}

	return;
}

int main()
{
	while (cin >> n)
	{
		flag = 0;
		memset(a, 0, sizeof(a));
		memset(vis, 0, sizeof(vis));
		for (int i = 0; i < n; i++)
			cin >> a[i];
		
		cin >> k;
		dfs(0);
		if (flag == 0)
		{
			cout << "No" << endl;
		}
	}

	return 0;

}
运行结果如下:

在这里插入图片描述

例题:POJ.2386:

Lake Counting
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 53321 Accepted: 26073
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 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
    Hint
    OUTPUT DETAILS:
    There are three ponds: one in the upper left, one in the lower left,and one along the right side.

题目思路:

本题是要你找出水洼个数W,并且W的上,下,左,右,及左上,左下,右上,右下,这八个部分表示同一个水洼,我们只需用深度优先搜索,搜索它的这些部分的所有W,然后搜索次数则为遍历次数,每搜索到一个W时则让这个W变为’ . '。

AC代码如下:

#include<iostream>
using namespace std;
const int maxn = 105;
char field[maxn][maxn];

int n, m;
void dfs(int x, int y)
{
	field[x][y] = '.';//将当前的w变为点
	for (int dx = -1; dx <= 1; dx++)
	{
		for (int dy = -1; dy <= 1; dy++)
		{
			int nx = x + dx; int 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 ans = 0;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (field[i][j] == 'W')
			{
				dfs(i, j);
				ans++;
}
}
}
	cout << ans << endl;
	return 0;
}

再看一道中等题:

【CodeForces】510B - Fox And Two Dots(bfs)

Fox Ciel is playing a mobile puzzle game called “Two Dots”. The basic levels are played on a board of size n × m cells, like this:
在这里插入图片描述
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.

The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, …, dk a cycle if and only if it meets the following condition:

These k dots are different: if i ≠ j then di is different from dj.
1.k is at least 4.
2.All dots belong to the same color.
3.For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.
Determine if there exists a cycle on the field.

Examples
Input
3 4
AAAA
ABCA
AAAA
Output
Yes
Input
3 4
AAAA
ABCA
AADA
Output
No
Input
4 4
YYYR
BYBY
BBBY
BBBY
Output
Yes
Input
7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB
Output
Yes
Input
2 13
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
Output
No
Note
In first sample test all ‘A’ form a cycle.
In second sample there is no such cycle.
The third sample is displayed on the picture above (‘Y’ = Yellow, ‘B’ = Blue, ‘R’ = Red).

本题思路:就是找出相同字母所能围成的圈且相同字母的个数为四。采用深搜,找到相同的则继续向下遍历一直到最后,看最后的那个字母是否与初始的相同,如果相同则输出YES,反之则继续遍历,最终没有找到则输出NO。

AC代码如下:

#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 50;
char a[maxn][maxn];
int vis[maxn][maxn];
int dir[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
int flag;
int ex, ey;
int nx, ny;
int n, m;
void dfs(int x, int y,int n1)
{
	if (flag)return;

	vis[x][y] = 1;
	
	for(int i = 0; i < 4; i++)
	{		//如果初始的坐标与最后的坐标相等且大于三个相同字母flag=1
		if (ex==nx&&ey==ny&& n1 > 2)
		{	//n1从零开始计数大于二即可
			flag = 1;
			return;
		}

		nx = x + dir[i][0];
		ny = y + dir[i][1];
		if (!vis[nx][ny]&&nx >= 0 && nx < n&&ny >= 0 && ny <m&&a[x][y] == a[nx][ny])
			dfs(nx, ny, n1 + 1);
	}
}

int main()
{
	while (cin >> n >> m)
	{

		flag = 0;

		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < m; j++)
			{
				cin >> a[i][j];
			}
		}
		for (int i = 0; i < n&&!flag; i++)
		{
			for (int j = 0; j < m&&!flag; j++)
			{
				memset(vis, 0, sizeof(vis));//每次搜索完成初始化vis
				ex = i, ey = j;
				dfs(i, j, 0);
			}
		}
		if (flag)
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
	}
		return 0;
	}


运行结果如下:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值