C语言BFS模板

广度优先算法对于求解最优解问题方面,应用广泛,现给出常用模板用于参考:

#define MAX_MN 300
#define MAX_STORE_NUM 90000
#define MAX_DIRECTION_NUM 4
typedef struct {
    int x;
    int y;
} PosStr;

#define MAX_ROW 50
#define MAX_COL 50
#define MAX_NUM MAX_ROW * MAX_COL
#define MAX_DIR_NUM 4
int direction[MAX_DIR_NUM][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

int NearestWareHouse(int **arr, int m, int n)
{
    int ret = 0;
    PosStr queue[MAX_STORE_NUM] = {0};
    memset(queue, 0, sizeof(PosStr) * MAX_STORE_NUM);
    int head = 0;
    int tail = 0;
    int vis[MAX_MN][MAX_MN] = {0};
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (arr[i][j] == 0) {
                queue[tail].x = i;
                queue[tail].y = j;
                tail++;
            }
        }
    }
    int dis = 0;
    while (head < tail) {
        int len = tail - head;
        for (int i = 0; i < len; i++) {
            PosStr temp = queue[head++];
            for (int j = 0; j < MAX_DIRECTION_NUM; j++) {
                int nextx = temp.x + direction[j][0];
                int nexty = temp.y + direction[j][1];
                if (nextx < 0 || nextx >= m || nexty < 0 || nexty >= n || arr[nextx][nexty] != 1 || vis[nextx][nexty] == 1) {
                    continue;
                }
                queue[tail].x = nextx;
                queue[tail++].y = nexty;
                ret += (dis + 1);
                vis[nextx][nexty] = 1;
            }
        }
        dis++;
    }
    return ret;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小朋友的大哈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值