hdu1312 Red and Black(搜索基础)

本文通过一个具体的迷宫问题实例,对比展示了深度优先搜索(DFS)与广度优先搜索(BFS)两种算法的应用及实现过程。文章首先介绍了DFS算法的递归实现方式,并通过代码详细解释了其工作原理;随后,又给出了BFS算法的队列实现方法,同样附带完整的源代码。通过对这两种算法的实际应用,读者可以更好地理解它们的特点和适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

难得不会做,还是从基础的做起吧。

注意本题是起点也算答案的一个。

dfs法:

#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;

const int N = 30;
const int INF = 1000000;

char Map[N][N];
int m, n, num;

int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

void dfs(int x, int y)
{
    num ++;
    for(int i = 0; i < 4; i++)
    {
        int dx = x + dir[i][0];
        int dy = y + dir[i][1];
        if(dx >= 0 && dx < m && dy >= 0 && dy < n && Map[dx][dy] == '.')
        {
            Map[dx][dy] = '#';
            dfs(dx, dy);
        }
    }
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    int x, y;
    while(~scanf("%d%d", &n, &m) && m!=0 && n!=0)
    {
        num = 0;
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
                cin >> Map[i][j];
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
            {
                if(Map[i][j] == '@')
                {
                    x = i;
                    y = j;
                }
            }
        dfs(x, y);
        printf("%d\n", num);
    }
    return 0;
}


bfs法:

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;

const int N = 30;
const int INF = 1000000;

char Map[N][N];
int m, n, num;

int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

struct node
{
    int x, y;
};

queue <node> q;

void bfs()
{
    while(!q.empty())
    {
        num ++;
        node tmp = q.front();
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            node tmp2;
            tmp2.x = tmp.x + dir[i][0];
            tmp2.y = tmp.y + dir[i][1];
            if(tmp2.x >= 0 && tmp2.x < m && tmp2.y >= 0 && tmp2.y < n && Map[tmp2.x][tmp2.y] == '.')
            {
                Map[tmp2.x][tmp2.y] = '#';
                q.push(tmp2);
            }
        }
    }
}

int main()
{
 //   freopen("in.txt", "r", stdin);
    int x, y;
    while(~scanf("%d%d", &n, &m) && m!=0 && n!=0)
    {
        num = 0;
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
                cin >> Map[i][j];
        node tmp;
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++)
            {
                if(Map[i][j] == '@')
                {
                    tmp.x = i;
                    tmp.y = j;
                }
            }
        q.push(tmp);
        bfs();
        printf("%d\n", num);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值