现在的位置: 首页 > 综合 > 正文

poj 1562 Oil Deposits(搜索,种子填充法)

2013年10月12日 ⁄ 综合 ⁄ 共 1109字 ⁄ 字号 评论关闭
简单的一道搜索题,可DFS可BFS 主要利用的搜索本身扩散的性质
一次搜素“一块”,并把搜索过的全部标记,只要记录下调用了多少次搜索即可
PASS: 题目中最后一组数据在数字后面多一个空格,我一开始用的是scanf %c读取数据,结果导致后面的char型信息全部读乱了,但不影响提交的结果。就是纠结了好长时间。。。。
用cin读取时不会读取空格。
scanf %s也不会读空格
#include<cstdio>

#include<cstring>

#include<queue>

#include<iostream>

using namespace std;

int n,m;

const int Maxsize = 105;

int maze[Maxsize][Maxsize];

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

typedef struct
{
    int x,y;
}node;

int main()
{
    void bfs(node start);
    char ch;
    int cnt;
    node start;
    while(scanf("%d %d",&n,&m) && n && m)
    {
        cnt = 0;
        memset(maze,0,sizeof(maze));
        for(int i = 0 ; i < n ; i ++)
        {
            getchar();
            for(int j = 0 ; j < m ; j++)
            {
                cin>>ch;
                if(ch == '*')           //记录矩阵的信息。
                {
                    maze[i][j] = 1;
                }
            }
        }
        for(int i = 0 ; i < n ; i++)
        {
            for(int j = 0 ; j < m ; j++)
            {
                if(!maze[i][j])
                {
                    start.x = i;start.y = j; //每出现一次可以搜索的点,用bfs对其八个方向进行全搜索
                    maze[i][j] = 1;//对矩阵的信息进行修改,一次可使“一块”搜索修改完毕
                    bfs(start);
                    cnt++;
                }
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}
void bfs(node start)
{
    node pre,cur;
    pre = start;
    queue<node>q;
    q.push(pre);
    while(!q.empty())
    {
        pre = q.front();
        q.pop();
        for(int i = 0 ; i < 8 ; i++)
        {
            cur.x = pre.x + dir[i][0];
            cur.y = pre.y + dir[i][1];
            if(maze[cur.x][cur.y])continue;
            if(cur.x < 0 || cur.x >=n || cur.y < 0 || cur.y >= m)continue;
            maze[cur.x][cur.y] = 1;
            q.push(cur);
        }
    }
}

抱歉!评论已关闭.