广度优先算法对于求解最优解问题方面,应用广泛,现给出常用模板用于参考:
#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;
}