zoukankan      html  css  js  c++  java
  • BFS进阶题,水陆距离

    给定一个N x M的01矩阵,其中1表示陆地,0表示水域。对于每一个位置,求出它距离最近的水域的距离是多少。

    矩阵中每个位置与它上下左右相邻的格子距离为1。

    Input
    第一行包含两个整数,N和M。

    以下N行每行M个0或者1,代表地图。

    数据保证至少有1块水域。

    对于30%的数据,1 <= N, M <= 100

    对于100%的数据,1 <= N, M <= 800

    Output
    输出N行,每行M个空格分隔的整数。每个整数表示该位置距离最近的水域的距离。

    Sample Input
    4 4
    0110
    1111
    1111
    0110
    Sample Output
    0 1 1 0
    1 2 2 1
    1 2 2 1
    0 1 1 0

    思路:按照BFS的特性,当以一个端点为中心向四周搜索完毕后,转而以另一个同类型的端点为中心继续搜索。所以我们可以先把0的点记录下来,
    然后从0点开始搜索,周围陆地离水的距离是1,等待几个0点搜索完,再以1为端点往下搜索。。。

    代码如下,使用队列q储存结构体的数据,用mapp[][]储存距离,首先把0点储存了。

    include <string.h>

    include <stdio.h>

    include

    include

    using namespace std;
    struct L
    {
    int x,y,s;
    } st,en;
    int n,m,mapp[810][810];
    int to[4][2]= {0,1,1,0,-1,0,0,-1};
    char map[810][810];
    queueq;
    void bfs()
    {
    int i,j;
    while(!q.empty() )
    {
    st=q.front();
    q.pop() ;
    for (i=0; i<4; i++)
    {
    en.x=st.x+to[i][0];
    en.y=st.y+to[i][1];//两个结构体,一个用来做端点,一个用来做往下搜索的点,
    //当然也可以用以前经常用的dx,dy等,但是太麻烦了,直接用一个结构体替代
    if (en.x>=0&&en.x<n&&en.y>=0&&en.y<m&&mapp[en.x][en.y]==-1)
    {
    en.s=st.s+1;
    mapp[en.x][en.y]=en.s;
    q.push(en);
    }
    }
    }
    for (i=0; i<n; i++)
    {
    for (j=0; j<m; j++)
    {
    printf("%d ",mapp[i][j]);
    }
    printf(" ");
    }
    }

    int main()
    {
    int i,j;
    scanf("%d %d",&n,&m);
    memset(mapp,-1,sizeof(mapp));
    for (i=0; i<n; i++)
    {
    scanf("%s",map[i]);
    for (j=0; j<m; j++)
    {
    if (map[i][j]=='0')
    {
    st.x=i;
    st.y=j;
    st.s=0;
    mapp[i][j]=0;
    q.push(st);
    }
    }
    }
    bfs();
    return 0;
    }

  • 相关阅读:
    周末之个人杂想(十三)
    PowerTip of the DaySorting Multiple Properties
    PowerTip of the DayCreate Remoting Solutions
    PowerTip of the DayAdd Help to Your Functions
    PowerTip of the DayAcessing Function Parameters by Type
    PowerTip of the DayReplace Text in Files
    PowerTip of the DayAdding Extra Information
    PowerTip of the DayPrinting Results
    Win7下IIS 7.5配置SSAS(2008)远程访问
    PowerTip of the DayOpening Current Folder in Explorer
  • 原文地址:https://www.cnblogs.com/shidianshixuan/p/13771730.html
Copyright © 2011-2022 走看看