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

BFS

2018年02月23日 ⁄ 综合 ⁄ 共 1868字 ⁄ 字号 评论关闭

纪念我的第一篇bfs,早就听说c++里面的标准包比较好……一直木有用过,这次用了里面的队列,队列的用法也就依托这个学习的……

#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<iostream>
#include<memory.h>
#include<limits.h>
#include<string.h>
using namespace std;
struct str
{
    int x;
}a[10];
int main()
{
    str s;
    queue <str>q;              //声明《 》里面为类型 
    for(int i=0;i<10;i++)
    {
        a[i].x=i;
        q.push(a[i]);          //入队
    }
    cout << q.size() << endl;  //队列长度
    s=q.front();               //访问第一个元素
    cout << s.x << endl;   
    q.pop();                   //出队
    s=q.front();
    cout << s.x << endl;
    s=q.back();                //访问最后一个元素
    cout << s.x << endl;
}

图像有用区域

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
描述

“ACKing”同学以前做一个图像处理的项目时,遇到了一个问题,他需要摘取出图片中某个黑色线圏成的区域以内的图片,现在请你来帮助他完成第一步,把黑色线圏外的区域全部变为黑色。

     

                图1                                                        图2 

已知黑线各处不会出现交叉(如图2),并且,除了黑线上的点外,图像中没有纯黑色(即像素为0的点)。

输入
第一行输入测试数据的组数N(0<N<=6)
每组测试数据的第一行是两个个整数W,H分表表示图片的宽度和高度(3<=W<=1440,3<=H<=960)
随后的H行,每行有W个正整数,表示该点的像素值。(像素值都在0到255之间,0表示黑色,255表示白色)
输出
以矩阵形式输出把黑色框之外的区域变黑之后的图像中各点的像素值。
样例输入
1
5 5
100 253 214 146 120
123 0 0 0 0
54 0 33 47 0
255 0 0 78 0
14 11 0 0 0
样例输出
0 0 0 0 0
0 0 0 0 0
0 0 33 47 0
0 0 0 78 0
0 0 0 0 0

##代码如下

题挺简单的,基本的BFS遍历……

 
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<queue>
#include<limits.h>
#include<memory.h>
#define MAX a>b?a:b;
using namespace std;
#define MA 0x3f3f3f3f
struct ff
{
    int x,y;
};
queue <ff> que;
int a[2000][2000],w,h;
int check(int i,int j)
{
    if(i<0||j<0||i>h+1||j>w+1||a[i][j]==0)
        return 0;
    else
    {
        a[i][j]=0;
        return 1;
    }
}
int bfs()
{
    ff n,m;
    int i,j;
    //cout<<que.size()<<endl;
    n.x=0;n.y=0;
    que.push(n);
    //cout<<que.size()<<endl;
    while(que.size())
    {
        m=que.front();
        que.pop();
        i=m.x;j=m.y;
        if(!check(i,j))
            continue;
        n.x=i+1;n.y=j;
        que.push(n);
        n.x=i-1;n.y=j;
        que.push(n);
        n.x=i;n.y=j+1;
        que.push(n);
        n.x=i;n.y=j-1;
        que.push(n);
    }

}
int main()
{
    int n,i,j,s;
    scanf("%d",&n);
    while(n--)
    {
            scanf("%d%d",&w,&h);
            for(i=0;i<=w+1;i++)
            {
                a[0][i]=1;
                a[h+1][i]=1;
            }
            for(j=1;j<=h;j++)
            {
                    a[j][0]=1;
                    for(s=1;s<=w;s++)
                    {
                        scanf("%d",&a[j][s]);
                    }
                    a[j][w+1]=1;
            }
            bfs();
            for(j=1;j<h+1;j++)
            {
                    for(s=1;s<w+1;s++)
                    {
                            printf("%d ",a[j][s]);
                    }
                    printf("\n");
            }
    }
    return 0;
}
        

抱歉!评论已关闭.