P1256 显示图像(广搜)

题意:略

思路,先说如何建树吧。广搜很简单,就是一个队列+一个检测数组。但是本质还是对搜索树的构建。

这里的构建就是一个节点有4个孩子,每个孩子代表4个方向就构成了一个搜索树。根据题目的就离公式转化一下,就是未被搜索的距离=最相邻已经被搜索的节点+1

代码:

#include<iostream>
#include<cstring>
#include<string>
using namespace std;

int n, m;
struct node{
    int x, y;
}a[1000010];
//维护一个队列来记录进队顺序
bool f[1010][1010];
//标记没有搜索过的
int d[1010][1010];
//这个点就是,用来存最短距离的,初值全为0
int dx[5] = { 0, 0, 0, -1, 1 }, dy[5] = { 0, -1, 1, 0, 0 };
//方向数组是一个小技巧,学会发挥很大的威力
int tail = 0, head = 0;
//队头,队尾
char s[1010];

int main(){
    memset(f, true, sizeof(f));
    //初始化全为true,标记过
    cin >> n >> m;
    for (int i = 1; i <= n; ++i)
    {
        cin >> s;
        //读入本行的所有元素
        for (int j = 0; s[j];++j)
        if (s[j] == '0')
            f[i][j + 1] = 0;//如果是0则表示没有访问过
        else{
            d[i][j + 1] = 0;
            f[i][j + 1] = true;
            a[++tail].x = i;
            a[tail].y = j + 1;
            //入队
        }
    }
    //按队的顺序开始搜索
    for (head = 1; head <= tail; ++head)
    {
        for (int i = 1; i <= 4; ++i)//用direct数组来向四方扩展
        {
            int xx = a[head].x + dx[i], yy = a[head].y + dy[i];
            //方向数组的用处就在这里了。
            if (!f[xx][yy]){
                d[xx][yy] = d[a[head].x][a[head].y] + 1;
                //这个点的距离=队头距离+1
                f[xx][yy] = true;
                //标记访问过的
                a[++tail].x = xx;
                a[tail].y = yy;
            }
        }
    }
    //d数组就是距离,现在可以输出了
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= m; ++j)
            cout << d[i][j] << " ";
        cout << endl;
    }
}
原文地址:https://www.cnblogs.com/ALINGMAOMAO/p/10394271.html