HDU 1312 Red and Black

本文提供了一道关于深度优先搜索(DFS)和广度优先搜索(BFS)的经典算法题目的实现方案。通过两个不同的方法解决同一个问题,帮助读者理解这两种搜索算法的基本原理及应用。
题目连接: 

http://acm.hdu.edu.cn/showproblem.php?pid=1312

 

//深度优先搜索
#include <iostream>
using namespace std;

char map[30][30];
int dir[][2]={{1,0},{-1,0},{0,1},{0,-1}};

int M, N, countn;


void dfs(int x, int y)
{
    int i;
    int X, Y;
    if(map[x][y]=='#')
    {
        return;
    }
    else
    {
        map[x][y]='#';
        countn++;
        for(i = 0; i < 4; i++)
        {
            X = x + dir[i][0];
            Y = y + dir[i][1];
            if(X>=0&&X<N&&Y>=0&&Y<M&&map[X][Y]!='#')
            {
                dfs(X, Y);
            }
        }
    }
}
int main()
{
    int i, j;
    int sx, sy;
    while(cin>>M>>N,M+N)
    {
        for(i = 0; i < N; i++)
        {
            for(j = 0; j < M; j++)
            {
                cin>>map[i][j];
                if(map[i][j]=='@')
                {
                    sx = i;
                    sy = j;
                }
            }
        }
        countn = 0;
        dfs(sx, sy);
        cout<<countn<<endl;
    }
}

 

//广度优先搜索
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
#define MAXN 25
char mapmap[MAXN][MAXN];
int visited[MAXN][MAXN];
int w, h;

struct point
{
    int x, y;
};

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

 

 

int main()
{

    int i, j;
    point cur, temp, p;
    while (cin >> w >> h, w||h)
    {
        for (i = 0; i < h; i++)
        {
            for (j = 0; j < w; j++)
            {
                cin >> mapmap[i][j];
                if (mapmap[i][j] == '@')
                {
                    cur.x = i;
                    cur.y = j;
                }
            }
        }
        memset(visited, 0, sizeof (visited));
        num = 1;
        visited[cur.x][cur.y] = 1;
        queue<point> myqueue;
        myqueue.push(cur);
        while (!myqueue.empty())
        {
            temp = myqueue.front();
            myqueue.pop();
            for (i = 0; i < 4; i++)
            {
                int x = temp.x + dir[i][0];
                int y = temp.y + dir[i][1];
                if (!visited[x][y] && mapmap[x][y] == '.' && x >= 0 && x < h && y >= 0 && y < w)
                {
                    visited[x][y] = 1;
                    p.x = x;
                    p.y = y;
                    myqueue.push(p);
                    num++;
                }
            }
        }
        cout << num << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值