DFS深度优先搜索例题分析

2023-02-16,,,,

洛谷P1596 Lake Counting S

题面翻译

由于近期的降雨,雨水汇集在农民约翰的田地不同的地方。我们用一个 \(N\times M(1\times N\times 100, 1\leq M\leq 100)\) 的网格图表示。每个网格中有水(W) 或是旱地(.)。一个网格与其周围的八个网格相连,而一组相连的网格视为一个水坑。约翰想弄清楚他的田地已经形成了多少水坑。给出约翰田地的示意图,确定当中有多少水坑。

输入第 \(1\) 行:两个空格隔开的整数:\(N\) 和 \(M\)。

第 \(2\) 行到第 \(N+1\) 行:每行 \(M\) 个字符,每个字符是 W.,它们表示网格图中的一排。字符之间没有空格。

输出一行,表示水坑的数量。

输入格式

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.

输出格式

Line 1: The number of ponds in Farmer John's field.

题目分析

明显的八方向DFS题,主要过程与连通块问题模板基本一致,伪代码如下:

void dfs(int step,参数表){
自定义参数;
if(目标状态){
输出解/作计数、评价处理;
}
for(int i=1;i<=状态的拓展可能数;i++){
if(第i种状态拓展可行){
维护自定义参数;
dfs(step+1,参数表);
}
}
}

特别的,连通块问题记得对经过的点染色标记。

AC题解

#include<bits/stdc++.h>
using namespace std;
int n,m,dx[9]={0,0,1,1,1,0,-1,-1,-1},dy[9]={0,-1,-1,0,1,1,1,0,-1},ans=0; //打表
char s[200][200];
void dfs(int p, int q){
for(int i=1;i<=8;i++){
if(s[p+dx[i]][q+dy[i]]=='W'){
s[p+dx[i]][q+dy[i]]='.';
dfs(p+dx[i],q+dy[i]);
}
}
}
int main(){
memset(s,'.',sizeof(s));
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
getchar();
for(int j=1;j<=m;j++){
scanf("%c",&s[i][j]);
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(s[i][j]=='W'){
ans++;
s[i][j]='.';
dfs(i,j);
}
}
}
printf("%d",ans);
return 0;
}

#1239 字符序列

题目描述

从三个元素的集合[A,B,C]中选取元素生成一个N 个字符组成的序列,使得没有两个相邻的连续子序列相同,例:N=5时ABCBA 是合格的,而序列ABCBC与ABABC是不合格的,因为其中子序列BC,AB 是相同的。

输入格式

一个正整数N(1<=N<=15)。

输出格式

满足条件的N字符的序列总数。

题目分析

要点在于判断重复字符串,所以最好还要定义一个bool型函数check方便处理。

AC题解

#include<bits/stdc++.h>
using namespace std;
int n,ans;
char s[4]={'z','A','B','C'},tp[1000];
bool check(int step,int k){
bool flag=1;
tp[step]=s[k]; //将待处理的地方先赋值
for(int len=2;len<=step/2;len++){ //剪枝,从长度2开始遍历
flag=1;
for(int i=0;i<len;i++){
if(tp[step-i]!=tp[step-len-i]){
flag=0; //染色
break;
}
}
if(flag==1){
tp[step]='0';
return 0;
}
}
return 1;
}
void dfs(int step){
if(step>n){
ans++;
return ;
}
for(int i=1;i<=3;i++){
if(tp[step-1]!=s[i]&&check(step,i)){
dfs(step+1);
tp[step]='0';
}
}
}
int main(){
memset(tp,'0',sizeof(tp));
scanf("%d",&n);
dfs(1);
printf("%d",ans);
return 0;
}

DFS深度优先搜索例题分析的相关教程结束。

《DFS深度优先搜索例题分析.doc》

下载本文的Word格式文档,以方便收藏与打印。