博客版权已保护:转载请注明出处,谢谢。

简单搜索专题的笔记

回溯法一般都会是把函数定义为bool类型的,因为这样才可以在底层return true;

https://vjudge.net/contest/215603#problem/K

如果不是记录路径的回溯法的话,一般会把dfs或者bfs定义为void类型

 

 

数组类型的深度搜索问题,一般会用上打表并且bool flag[][]类型的数组也必不可少,用来记录路径,防止死循环

数组类型:https://vjudge.net/contest/215603#problem/C

 

 

二维数组或者是三维数组,也就是题目的input是以
***##.

**.##
这种形式给出的话,一般要定义一个结构体数组,这样的话,才可以把它的坐标做入栈或者入队处理。

还有一般这种问题都是要遍历4个或者6个或者是8个(三维)方向的,那么可以在一开始就定义一个数组dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};这样子,然后如果是用广度优先搜索的话,就可以遍历四个方向,确定要不要入队,不要就continue;
多维数组问题:https://vjudge.net/contest/215603#problem/B

以下是hdu 1241的题目:

 Oil Deposits

#include<queue>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int r,c;
char mp[105][105];
bool flg[105][105];
int dir[8][2]={{1,0},{0,1},{-1,0},{0,-1},{-1,-1},{-1,1},{1,1},{1,-1}};
struct node
{
    int x;
    int y;
};

void bfs(int x,int y)
{
    node no,ne;
    no.x=x;no.y=y;
    queue<node> q;
    q.push(no);
    while(q.size())
    {
        no=q.front();
        q.pop();
        for(int i=0;i<8;i++)
        {
            ne.x=no.x+dir[i][0];
            ne.y=no.y+dir[i][1];

            if(ne.x<0||ne.x>=r||ne.y<0||ne.y>=c||mp[ne.x][ne.y]=='*')  continue;

            if(!flg[ne.x][ne.y])
            {
                flg[ne.x][ne.y]=true;
                q.push(ne);
            }
        }
    }
}
int main()
{
    while(scanf("%d %d",&r,&c)!=EOF&&r&&c)
    {
        int ans=0;
        memset(mp,'*',sizeof(mp));
        memset(flg,false,sizeof(flg));

        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                cin>>mp[i][j];
        for(int i=0;i<r;i++)
        {
            for(int j=0;j<c;j++)
            {
                if(mp[i][j]=='@'&&!flg[i][j])
                {
                    bfs(i,j);
                    ans++;
                }
            }
        }

        printf("%d\n",ans);
    }
    return 0;
}

 

posted on 2018-04-13 18:34  superhero11  阅读(123)  评论(0编辑  收藏  举报

导航