dfs学习总结

今天做到了dfs的训练,感觉和bfs有相似之处,接下来用一道题来总结一下方法,可类比bfs。

上题:

Description

There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. 

Write a program to count the number of black tiles which he can reach by repeating the moves described above. 
 

Input

The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20. 

There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows. 

'.' - a black tile 
'#' - a red tile 
'@' - a man on a black tile(appears exactly once in a data set) 
 

Output

For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself). 
 

Sample Input

6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
 

Sample Output

45 59 6 13
 
解题代码:

#include<stdio.h>
#include<string.h>
char point[25][25];
bool flag[25][25];              //flag对应着我们需要研究的点point,用来标记是否曾经到过
int dx[4]={1,-1,0,0};
int dy[4]={0,0,-1,1};
int count;
void dfs(int x0,int y0,int r,int c)
{
    for(int i=0;i<4;i++)        //for循环用来探索所有邻接点
    {
        int tempx=x0+dx[i],tempy=y0+dy[i];
        if(tempx<c&&tempx>=0&&tempy<r&&tempy>=0&&flag[tempy][tempx]==false&&point[tempy][tempx]=='.')
        {
            count++;
            flag[tempy][tempx]=true;        //满足条件且未标记的标记上
            dfs(tempx,tempy,r,c);           //通过递归来实现顺藤摸瓜的效果
        }
    }
    return ;
}
void make_set()
{
    for(int i=0;i<25;i++)
        for(int j=0;j<25;j++)
            flag[i][j]=false;
    return ;
}
int main()
{
    int c,r,x0,y0;
    while(1)
    {
        count=1;
        scanf("%d%d",&c,&r);
        getchar();
        if(c==0&&r==0)
            break;
        for(int i=0;i<r;i++)
        {
            for(int j=0;j<c;j++)
            {
                point[i][j]=getchar();
                if(point[i][j]=='@')
                {
                    x0=j;
                    y0=i;
                }
            }
            getchar();
        }
        make_set();
        dfs(x0,y0,r,c);
        printf("%d\n",count);
    }
    return 0;
}

与bfs的区别:bfs是通过队列来进行逐层探索,而dfs则是沿着一个路径探索下去一直到底,到底后再返回沿其他路径探索,就和顺藤摸瓜差不多,大体上两者达到的效果基本一致(特殊情况效果有区别),两者均有缺点,bfs在编写代码时较麻烦,用到队列,一般要使用结构体,而dfs则是由于其使用递归调用,大数据易超时。

==================================================================================================================================

赶紧跑回来加一句:最短路径用bfs!!



### C++ 中 DFS 和 BFS 算法的学习与实践 #### 一、基础知识概述 深度优先搜索 (Depth First Search, DFS) 和广度优先搜索 (Breadth First Search, BFS) 是两种基本的图遍历算法。DFS 主要采用栈结构来实现,而 BFS 则依赖队列完成遍历过程。 对于大规模数据集而言,这两种算法各有特点: - **DFS 特点** - 能够快速找到深度优先的路径。 - 更适合于需要沿一条路径尽可能深地探索的应用场景[^3]。 - **BFS 特点** - 找到最短路径的能力使其成为处理距离计算的理想选择。 - 遍历离起始节点较近的节点效率高,但在大型网络中占用较多内存资源[^2]。 #### 二、具体应用场景分析 这些算法不仅限于理论研究,在实际编程中有广泛用途: - 图像识别领域内的连通区域标记可以借助 DFS 或者 BFS 来高效执行; - 迷宫游戏设计里利用它们模拟玩家移动路线规划; - 社交媒体平台好友推荐机制也离不开此类技术的支持; 此外,还有更多有趣的实例等待开发者挖掘并应用于项目开发之中。 #### 三、C++ STL 库支持下的代码样例展示 下面分别给出了基于标准模板库(Standard Template Library, STL)容器类 vector<int> 表达邻接表形式存储图形结构下简单的 DFS 和 BFS 函数定义及其调用方式说明。 ##### (一)DFS 实现 ```cpp #include <iostream> #include <vector> using namespace std; void dfs(const int& node, const vector<vector<int>>& adjList, vector<bool>& visited){ cout << "Visit Node:" << node << endl; visited[node]=true; // Mark current vertex as visited for(auto neighbor : adjList[node]){ if(!visited[neighbor])// If adjacent vertices haven't been traversed yet, dfs(neighbor,adjList,visited); // Recursively visit them. } } ``` 此函数接收三个参数:当前顶点编号 `node` ,表示图关系的数据结构 `adjList` 以及记录访问状态的一维布尔数组 `visited[]`. ##### (二)BFS 实现 ```cpp #include <queue> void bfs(int startNode,vector<vector<int>> &graph,bool *isVisited,int n){ queue<int> q; isVisited[startNode]=true;q.push(startNode); while (!q.empty()){ auto currentNode=q.front();cout<<"Visiting:"<<currentNode<<endl;q.pop(); for(size_t i=0;i<graph[currentNode].size();++i){ if(!isVisited[graph[currentNode][i]]){ isVisited[graph[currentNode][i]]=true; q.push(graph[currentNode][i]); } } } } ``` 上述程序片段展示了如何运用 STL 提供的标准容器——双端队列(queue),配合逻辑运算符轻松构建出完整的广搜框架[^1]. #### 四、总结建议 为了更好地掌握这两项技能,除了反复练习编写相关题目外,还应该注重理解其背后的原理概念,并尝试将其与其他知识点相结合创造出更复杂的解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值